听一下keydown的时刻(就在键从上到下变化的时候)?

时间:2012-12-14 00:05:09

标签: javascript

我尝试使用keydown和keypress,但如果用户持有密钥则会不断触发。有没有办法只监听用户按下键的时间(从未按下按钮变为按下),以便例如:按住键激活代码一次并按下它,释放它并再次按下2次?

我正在使用它来检查哪些键已关闭:

$(document).keydown(function (e){
    console.log(e.which);
});

2 个答案:

答案 0 :(得分:1)

您可以在keydown的第一次调用时取消绑定keydown处理程序,然后在keyup上重新绑定它。

// keydown is bound at load
$(document).keydown(function (e){
    // Call function
    doStuff();
});

// keyup rebinds the keydown event.
$(document).keyup(function(e) {
   $(document).keydown(function(e) {
     doStuff();
   });
});

// The function called on keydown does something
// and then unbinds the keydown event
function doStuff() {
   console.log("Doing stuff");
   // And unbind it...
    $(document).unbind('keydown');
}

http://jsfiddle.net/cbSRu/2/

答案 1 :(得分:0)

这是我最终使用的,好处是它可以影响所有键或只是其中一些键添加循环:

var keys = {};
var keyPressed = {};
$(document).keydown(function (e){
    if(!keyPressed[e.which]) { keyPressed[e.which] = true; keys[e.which] = true; } // If you add disableKey(e.which) here all keys are listened only once
});
$(document).keyup(function (e){
    delete keys[e.which];
    delete keyPressed[e.which];
});
function disableKey(n) {
    delete keys[n];
}
// Adding this function enables you to disable keys individually (probably have something like this anyway to differenciate keys)
function doStuff() {
    if(keys[65]) { console.log('attack'); disableKey(65); } // Disable key 65
    if(keys[83]) { console.log('jump'); }
    setTimeout(function(){doStuff()},100);
}
doStuff();​

http://jsfiddle.net/cbSRu/6/