JavaScript执行直到按下键

时间:2011-01-20 04:40:55

标签: javascript

我想执行一个循环/动作,直到按下一个键并且onpress我想停止该动作并调用函数getKey。有人可以建议怎么做吗?

function getKey(e) 
{
    var pressedKey;
    if (document.all)   { e = window.event; }
    if (document.layers || e.which) { pressedKey = e.which; }
    pressedCharacter = String.fromCharCode(pressedKey).toLowerCase();
    move(pressedCharacter);

}

document.onkeypress = getKey;

我希望move()函数连续执行,直到没有按下某个键。如果它被按下我想用新按下的字符

重新执行move()函数

2 个答案:

答案 0 :(得分:3)

取决于你如何循环。最简单的方法是使用interval

var interval = window.setInterval(function () {
    // do your thing, do your thing
}, 1000);

document.onkeypress = function () {
    if (/* some specific character was pressed */) {
        window.clearInterval(interval);

        // do some other thing, other thing
    }
};

答案 1 :(得分:1)

使用http://www.asquare.net/javascript/tests/KeyCode.html查找密钥代码

<script>
document.onkeyup = getKey;       

function getKey() {
    // If the users hits 'a', stop loopcode from running.
    if(event.keyCode == 65){
        window.clearInterval(interval);
    };
}

var interval = setInterval(function() {
    // loopcode here
}, 1000);

</script>
相关问题