按住"enter"键时如何防止触发按钮事件? [英] How to prevent triggering button event when press 'enter' key and hold?
问题描述
案例受到打击:
如果您单击该按钮,然后按住"enter"键并按住不放,则该按钮的click事件将不断触发.
If you click the button and then press 'enter' key and hold for it, the button's click event will trigger constantly.
document.querySelector('button').addEventListener('click', function (e) {
console.log(1);
})
<button>press Enter</button>
没有jQuery,没有表单,没有输入.我想知道这是如何工作的以及如何预防...
There's no jQuery, no form, no input. I wonder how this work and how to prevent it...
谢谢你.
推荐答案
之所以会发生这种情况,是因为按下按钮上的Enter会触发其点击事件,并且当您按住某个键时,重复键会插入并不断对该键进行输入"结束.
It happens because pressing Enter on a button triggers its click event, and when you hold a key, key repeat kicks in and keeps "typing" that key over and over.
如果要在触发一次事件后的一段时间内忽略该事件,可以将代码添加到处理程序中以执行此操作:
If you want to ignore the event for a period of time after it's been triggered once, you can add code to your handler to do that:
var IGNORE_TIME = 1000; // One second
var lastClick = null;
document.querySelector('button').addEventListener('click', function (e) {
var now = Date.now();
if (!lastClick || now - lastClick > IGNORE_TIME) {
lastClick = now;
console.log(1);
}
});
<button>press Enter</button>
如果您从不不想按按钮上的Enter键来点击"它(我不建议这样做,对于依靠键盘使用的残障人士来说,这可能会很困难),您可以防止按钮上的 keydown
事件:
If you never want pressing Enter on the button to "click" it (which I don't recommend, you may make it difficult for someone with a disability who relies on using the keyboard), you can prevent the keydown
event on the button:
document.querySelector('button').addEventListener('click', function (e) {
console.log(1);
});
document.querySelector('button').addEventListener('keydown', function (e) {
var key = e.keyCode || e.charCode;
if (key == 13) {
e.stopPropagation();
e.preventDefault();
}
});
<button>press Enter</button>
另请参见 vlaz的答案,它仅在按键重复时才阻止按键,这似乎是一个很好的折衷方案.
See also vlaz's answer, which only prevents the keypress if it's from key repeat, which seems like an excellent compromise.
这篇关于按住"enter"键时如何防止触发按钮事件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!