我需要创建一个在按下“A”或“D”键时移动的框。这是我到目前为止的代码:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function left(id)
{
var y = '-5';
var z =document.getElementById(id).style.left;
u = parseInt(y)+parseInt(z);
var state = document.getElementById(id).style.left;
document.getElementById(id).style.left = u;
}
function right(id)
{
var r = '5';
var z =document.getElementById(id).style.left;
u = parseInt(r)+parseInt(z);
var state = document.getElementById(id).style.left;
document.getElementById(id).style.left = u;
}
event.onkeyUp = KeyCheck();
function KeyCheck()
{
var KeyID = event.keyCode;
switch(KeyID)
{
case 97: left("y");
break;
case 100: right("y");
break;
}
}
</script>
</head>
<body>
<div style="position:absolute; height:50px; width:50px; left:100px; right:100px; top:500px; background-color:#03C;" id="y">
</div>
</body>
</html>
答案 0 :(得分:2)
I fixed your JavaScript for you:
//was: event.onkeyUp = KeyCheck(); calls KeyCheck(); assigns result!
document.onkeyup = KeyCheck; // assigns function object KeyCheck
//was: function KeyCheck() ignores Event object argument!
function KeyCheck(e) // need to inspect Event object that is passed
{
//was: var KeyID = event.keyCode; event is not related to this callback!
var KeyID = e.keyCode; // get keyCode property from passed object
switch(KeyID)
{
case 65: left("y"); // need to use ASCII codes for uppercase
break;
case 68: right("y");
break;
}
}
然而,作为Town suggests,有更好的方法来实现这一点(使用jQuery)。
答案 1 :(得分:1)
我知道您的问题被标记为纯JavaScript,很多人讨厌基于库的简单Javascript问题的答案,但我真的建议使用jQuery这样的库来做到这一点,这样你就不会不得不担心有关密钥代码处理和事件连接的浏览器问题。
<强>的jQuery 强>
$(document).keydown(function(e) {
var moveBy;
switch (e.which) {
case 65: // a
moveBy = -10;
break;
case 68: // d
moveBy = 10;
break;
}
$('div').css('left', function() {
var l = parseInt($(this).css("left"));
$(this).css("left", (l + moveBy) + "px");
});
});
值得注意的是,jQuery 1.6向css()
引入了相对值,这意味着您可以进一步简化该代码,但目前存在一个阻止其工作的错误 - 计划在1.6.2中修复