0

So I have the following code, which should append 'true' to the div "test" every 25ms as long as key 68 (the d key) is being pressed, right?

<html>
<body>
<div id="test"></div>
<script type="text/javascript">
var key=false;
var keyDown=function(e) {
 if (e.keyCode==68) {
  key=true;
 }
}
var keyUp=function(e) {
 if (e.keyCode==68) {
  key=false;
 }
}
document.onkeydown=keyDown;
document.onkeyup=keyUp;
var run=function() {
 document.getElementById('test').appendChild(document.createTextNode(key+'\n'));
 t = setTimeout('run()', 25);
}
var t = setTimeout('run()', 25);
</script>
</body>
</html>

Save the code, load it in a browser and hold down on the d key. If I'm not crazy, you'll see that it occasionally appends 'false' even though the d key was never released. (I've tried this in FF and Chrome in Linux and Vista). Anybody happen to know why, or have a workaround?

Edit: It seems to behave as expected in FF running in OS X.

4

1 回答 1

0

我只是在IE7中尝试过。将“e.keyCode”更改为“event.keyCode”后,它就像您预期的那样工作。

您是否真的尝试过您在此处粘贴的代码,或者您是否正在使用其他可能存在错误的代码?

编辑

我刚刚在 Chrome 中运行了这个。同样,它的行为符合预期。

您使用的无线键盘是否容易受到干扰或电池电量不足而不会影响键盘的正常使用,但在此测试中变得可见?

于 2010-04-01T20:22:07.713 回答