在 addEventListener 或 element.on* 附加的事件处理程序中“返回 false”

发布于 2024-09-13 18:49:03 字数 574 浏览 8 评论 0原文

好吧,让我们先解决这个问题。是的,我想隐藏上下文菜单。不,我并不是试图阻止有人从我的页面上窃取内容。其预期用途是浏览器内游戏的输入,并且仅限于网页上的特定区域。

从意识形态转向技术......

var mouse_input = function (evt) {
    // ...
    return false;
}

document.onmousedown = mouse_input; // successful at preventing the menu.
document.addEventListener('mousedown', mouse_input, true); // unsuccessful

有人可以向我解释为什么 addEventListener 版本无法阻止上下文菜单触发吗?我在 SafariWeb 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

一紙繁鸢 2024-09-20 18:49:03

于是,我徒劳的寻找突然变得富有成效。

var mouse_input = function (evt) {
    evt.preventDefault();
}

document.addEventListener('contextmenu', mouse_input, false);

适用于 SafariFirefoxOperapreventDefault() 阻止常见操作的发生。我必须更改监听的事件以适应 Safari,无论如何,它更符合逻辑。更多信息:实现 EventListener 不应返回值,因此 return false 无效。

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 Safari and it is more logical anyway. Further information: functions that implement EventListener shouldn’t return values so return false had no effect.

指尖凝香 2024-09-20 18:49:03

解释一下区别.. 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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文