问题描述
我只是在我的 上添加了一个
click
事件处理程序.
I'm only adding a click
event handler on my <button>
.
document.getElementsByTagName("button")[0].addEventListener("click", event => {
event.preventDefault();
console.log("Click:", event);
});
<button>Press <kbd>Enter</kbd> on me</button>
(演示链接)
尽管如此,当我在 Firefox 中按 Tab 键到按钮,然后按 ,我看到 click
事件被触发.但是,我无法在任何地方看到这种行为的记录.这是标准行为吗,我可以指望它在所有浏览器中都能正常工作吗?
Nevertheless, when I tab to the button in Firefox, then press , I see the click
event being fired. However, I cannot see this behaviour documented anywhere. Is this standard behaviour, and can I count on it working in all browsers?
推荐答案
这主要是因为历史上许多作者使用点击事件编写代码而忘记考虑不点击的用户(无论是因为他们更喜欢使用键盘导航,有残疾导致难以使用指点设备,或其他任何原因).
This is largely because lots of authors have historically written code using click events while forgetting to account for users who don't click (whether because they prefer to use a keyboard to navigate, have a disability which makes it hard to use a pointing device, or whatever other reason).
该行为记录在 HTML 规范中:
HTML 中的某些元素具有激活行为,这意味着用户可以激活它们.这会触发一系列取决于激活机制的事件,通常以点击事件结束,如下所述.
…
为了可访问性,键盘的 Enter 和 Space 键通常用于触发元素的激活行为.
For accessibility, the keyboard’s Enter and Space keys are often used to trigger an element’s activation behavior.
然后继续详细解释这些步骤.
It then goes on to explain the steps in detail.
这篇关于为什么在我的 <button> 上触发了“click"事件?当我按下 Enter 键时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!