在 addEventListener 或 element.on* 附加的事件处理程序中“返回 false”
好吧,让我们先解决这个问题。是的,我想隐藏上下文菜单。不,我并不是试图阻止有人从我的页面上窃取内容。其预期用途是浏览器内游戏的输入,并且仅限于网页上的特定区域。
从意识形态转向技术......
var mouse_input = function (evt) {
// ...
return false;
}
document.onmousedown = mouse_input; // successful at preventing the menu.
document.addEventListener('mousedown', mouse_input, true); // unsuccessful
有人可以向我解释为什么 addEventListener 版本无法阻止上下文菜单触发吗?我在 Safari 的 Web Inspector 中看到的唯一区别是 document.onmousedown
有一个 isAttribute
值为 true,而 addEventListener
版本的值为 false。
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 addEventListener
version is unable to stop the context menu from firing? The only difference I was able to see in Safari's Web Inspector was that document.onmousedown
had a isAttribute
value that was true whilst the addEventListener
version had the same value as false.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
于是,我徒劳的寻找突然变得富有成效。
适用于 Safari、Firefox、Opera。
preventDefault()
阻止常见操作的发生。我必须更改监听的事件以适应 Safari,无论如何,它更符合逻辑。更多信息:实现 EventListener 不应返回值,因此return false
无效。So my unfruitful search suddenly became fruitful.
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 Safari and it is more logical anyway. Further information: functions that implement EventListener shouldn’t return values soreturn false
had no effect.解释一下区别..
element.onmousedown = somefunction;
是绝对赋值;您正在替换元素上的事件处理程序。element.addEventListener(...)
,顾名思义,除了已经附加到事件的任何处理程序之外,还添加一个处理程序。To explain the difference ..
element.onmousedown = somefunction;
is an absolute assignment; you are replacing the event handler on the element.element.addEventListener(...)
is, as the name implies, adding a handler in addition to any handler(s) already attached for the event.