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。 –