我注意到鼠标右键单击 Firefox 会触发 addEventListener。
我在更多浏览器和更多操作系统(IE 11-10-9、Safari、Chrome)上尝试了这段代码,并通过鼠标右键单击,仅在 Firefox 上始终打印 console.log 消息。
<div id="one-div" style="height:400px;width:500px;background-color:#000;"> click me </div>
<script>
function cb(event, from){
// if click is fired on <div> with:
// left click, both EventListener will be printed.
// right click, only the 'document' one will be printed.
event.preventDefault();
console.log(event + ' from: ' + from );
}
document.addEventListener('click', function(e){
cb(e,'document');
}, false);
document.getElementById("one-div").addEventListener('click', function(e){
cb(e,'one-div');
}, false);
</script>
而且我还注意到,当单击被触发到 div 时,它只会触发 document.addEventListener。 我搜索了 Firefox 更新日志,但没有相关消息。
谁能解释这种行为? 谢谢!
最佳答案
默认情况下,在所有浏览器中,右键单击事件由
addEventListener('contextmenu')
,否则右键单击将打开一个带有一些选项的窗口(每个浏览器都有不同的选项)。
在 Firefox 中,当您将 addEventListener('click')
添加到 document
对象时,它将捕获文档,它将禁用 this右键单击行为。
另外,这就是Mozilla documentation在 Mouse Events 部分中说,虽然 (ANY button) 东西在您将监听器添加到 document
对象
click: A pointing device button (ANY button; soon to be primary button only) has been pressed and released on an element.
*注意:双击鼠标右键仍显示上述窗口,单击鼠标不显示。
关于javascript - 鼠标右键点击 Firefox 触发点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43144995/