Stop key from repeating on hold. (jQuery)

2020-07-06 08:36发布

Hello everyone i just picked up jQuery

So my question is i want to stop a key from repeating when you hold it down

Example: Edit (i want it to stop .. so 1 character per keypress/keydown)

keypress: a

HoldDown: aaaaaaaaaaaaaaaaaaaaaaaaaaaaa

My code is:

 <input type='text'>

var stop= false;
var time =null;
$(':text').keypress(function(e) {
if(stop === true){e.preventDefault();}
    if (time !== null) {
        lastkey = time;
    }
    time = new Date().getTime();
    var between = time - lastkey;
    if (between <= 70) {
        stop = true;
    }
});
$(':text').keyup(function(){stop = false;});

Am i going about this the wrong way?

标签: jquery
3条回答
We Are One
2楼-- · 2020-07-06 09:21

Use the .keyup() bind instead of .keypress().

查看更多
欢心
3楼-- · 2020-07-06 09:26

Try this: http://jsfiddle.net/maniator/yFA8c/

It will only allow a letter per every 2 seconds.

Code:

var mult = false,
    prev = 0;

$('.mult').keydown(function(e) {
    if (!mult) {
        mult = true;
        prev = e.which;
        setTimeout(function() {
            mult = false;
        }, 2000)
    }
    else if (prev != e.which) {
        mult = false;
    }
    else {
        return false;
    }
})​;​
查看更多
男人必须洒脱
4楼-- · 2020-07-06 09:27

You should use keydown and keyup events instead keypress.

So, here is a solution:

window.keypressed = {};
$('#element').keydown(function(e){
  if ( window.keypressed[e.which] ) {
    e.preventDefault();
  } else {
    window.keypressed[e.which] = true;
}).keyup(function(e){
  window.keypressed[e.which] = false;
});
查看更多
登录 后发表回答