Why does this javascript not move the box when keys are pressed, as expected? [closed]
I need to create a box that moves when the 'A' or 'D' keys are pressed. This is the code that I have so far:
<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>
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;
}
}
However, as Town suggests, there are better ways to accomplish this (with jQuery).
I know your question is tagged as plain JavaScript and many people hate library-based answers to plain Javascript questions, but i'd really recommend using a library such as jQuery to do this so that you don't have to worry about browser quirks regarding keycode handling and event hookups.
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");
});
});
Working Demo on jsfiddle.net
It's also worth noting that jQuery 1.6 introduced relative values to css()
which would mean that you could simplify that code even further, but there's currently a bug that prevents it from working - planned to be fixed in 1.6.2.
精彩评论