1
移动,我试图让一个框移动,当我按下箭头键。我发现this的解决方案,并试图将其复制,但它仍然无法正常工作(由森那维达斯顶端回答)。麻烦此框在JavaScript
我的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>
您试图访问'#pane'和'#box'存在才。请阅读http://stackoverflow.com/questions/14028959/why-does-jquery-or-a-dom-method-such-as-getelementbyid-not-find-the-element和jQuery的教程:HTTP:// docs.jquery.com/Tutorials:Getting_Started_with_jQuery。 –