javascript 由 addEventListener 或 element.on* 附加的事件处理程序中的`return false`
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/3462123/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
`return false` in an event handler attached by addEventListener or element.on*
提问by casr
Right let's get this out the way first. Yes, I want to hide the context menu. No, I'm not trying to prevent someone lifting content off my page. Its intended use is input for an in-browser game and it will be limited to a specific area on the webpage.
好吧,让我们先解决这个问题。是的,我想隐藏上下文菜单。不,我不是要阻止有人从我的页面上删除内容。它的预期用途是用于浏览器内游戏的输入,并且将仅限于网页上的特定区域。
Moving from the ideological to the technical...
从意识形态到技术...
var mouse_input = function (evt) {
// ...
return false;
}
document.onmousedown = mouse_input; // successful at preventing the menu.
document.addEventListener('mousedown', mouse_input, true); // unsuccessful
Could someone explain to me why the addEventListenerversion is unable to stop the context menu from firing? The only difference I was able to see in Safari's Web Inspectorwas that document.onmousedownhad a isAttributevalue that was true whilst the addEventListenerversion had the same value as false.
有人可以向我解释为什么该addEventListener版本无法阻止上下文菜单触发吗?我能够在Safari的Web Inspector 中看到的唯一区别是,document.onmousedown它的isAttribute值为 true 而addEventListener版本具有与 false 相同的值。
采纳答案by casr
So my unfruitful search suddenly became fruitful.
于是,我徒劳的寻找突然变得富有成效。
var mouse_input = function (evt) {
evt.preventDefault();
}
document.addEventListener('contextmenu', mouse_input, false);
Works for Safari, Firefox, Opera. preventDefault()stops the usual actions from happening. I had to change the event that was listened for to accommodate for Safariand it is more logical anyway. Further information: functions that implement EventListenershouldn't return values so return falsehad no effect.
适用于Safari、Firefox、Opera。preventDefault()阻止通常的动作发生。我不得不更改侦听的事件以适应Safari,无论如何它更合乎逻辑。更多信息:实现EventListener 的函数不应该返回值,所以return false没有效果。
回答by Stephen P
To explain the difference .. element.onmousedown = somefunction;is an absolute assignment; you are replacingthe event handler on the element. element.addEventListener(...)is, as the name implies, addinga handler in addition to any handler(s) already attached for the event.
解释差异 ..element.onmousedown = somefunction;是一个绝对的任务;您正在替换元素上的事件处理程序。element.addEventListener(...)顾名思义,就是在已经为事件附加的任何处理程序之外添加一个处理程序。

