2

我尝试使用 keydown 和 keypress 但如果用户按住键,两者都会不断触发。有没有办法只听用户按下键(从未按下变为按下),以便例如:按住键触发代码一次并按下它,释放它并再次按下它2次?

这就是我用来检查哪些键关闭的方法:

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

2 回答 2

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/

于 2012-12-14T00:09:01.963 回答
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/

于 2012-12-14T01:13:58.777 回答