当我按下箭头键时,我试图让一个盒子移动。我找到了这个解决方案并试图将其复制进去,但它仍然不起作用(Sime Vidas 的最佳答案)。
我的 Jquery 文件肯定在同一个文件夹中,其他所有内容都只是从解决方案中复制和粘贴(在 JSFiddle 演示中有效)。所以我想问题不是 HTML、CSS 或 JavaScript,而是我把它们放在一起时犯了一些错误。
盒子出现了,但没有移动。为什么它不起作用?
<!doctype html>
<html>
<head>
<style>
#pane {
    position:relative;
    width:300px; height:300px;
    border:2px solid red;
}  
#box {
    position:absolute; top:140px; left:140px;
    width:20px; height:20px;          
    background-color:black;
}
</style>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
var pane = $('#pane'),
    box = $('#box'),
    maxValue = pane.width() - box.width(),
    keysPressed = {},
    distancePerIteration = 3;
function calculateNewValue(oldValue, keyCode1, keyCode2) {
    var newValue = parseInt(oldValue, 10)
                   - (keysPressed[keyCode1] ? distancePerIteration : 0)
                   + (keysPressed[keyCode2] ? distancePerIteration : 0);
       return newValue < 0 ? 0 : newValue > maxValue ? maxValue : newValue;
}
$(window).keydown(function(event) { keysPressed[event.which] = true; });
$(window).keyup(function(event) { keysPressed[event.which] = false; });
    setInterval(function() {
    box.css({
        left: function(index ,oldValue) {
            return calculateNewValue(oldValue, 37, 39);
        },
        top: function(index, oldValue) {
            return calculateNewValue(oldValue, 38, 40);
        }
    });
}, 20);
</script>
</head>
<body>
<div id="pane">
    <div id="box"></div>
</div>
</body>
</html>