停止点击事件传播 [英] Stop click event propagation

查看:65
本文介绍了停止点击事件传播的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在用户单击某个网页时突出显示该网页的任何DOM元素。为此,我遍历当前元素的所有元素并禁用任何功能(例如,我可以单击而不进行重定向):

I'm trying to highlight any DOM element of a certain Web page when the user clicks on it. For that purpose, I iterate through all elements of the current element and disable any functionality (so e.g. I can click and not to be redirected):

var elems = window.document.getElementsByTagName('*');
for (var i = 0; i < elems.length; i++) {
    elems[i].onclick = function(e){ 
        e.preventDefault();
}

问题是,当用户单击时,会触发很多点击事件,因为每个元素都有tas行为,所以我需要避免引起人们的注意。

The thing is, when user clicks, a lot of click events are fired, because every element has tas behaviour, and I need to avoid unhighlight.

有什么想法可以改善它或任何其他选择?
非常感谢!

Any idea of how to improve that or any alternative? Thanks a lot!

P / d:必须是纯JS

P/d: It has to be pure JS

推荐答案

您需要做两件事:首先,您要实际添加一个事件,而不是重新定义其点击行为,其次,您希望它不要通过dom 起泡。试试:

You'll need to do two things: first of all, you want to actually add an event, not redefine its click behaviour, and secondly, uou want it to not bubble up through the dom. Try this:

var elems = window.document.getElementsByTagName('*');
for (var i = 0; i < elems.length; i++) {
    // Use addEventListener to listen for events.
    // Older version of IE use attachEvent, but I guess thats irrelevant.
    elems[i].addEventListener("click", function(e){
        e.preventDefault();
        // Use stopImmediatePropagation to stop the element from passing this click to wrapping parents - because a click on a child is technically a click on the parent as well.
        e.stopImmediatePropagation();
    });
}

更多内容请阅读:


添加事件监听器: https://developer.mozilla .org / zh-CN / docs / Web / API / EventTarget / addEventListener

停止立即传播: https://developer.mozilla.org/en-US/docs/Web/API/Event/stopImmediatePropagation

正如勇敢的编辑所说,您也可以将 false 作为第三个参数传递给 addEventListener ,它的功能基本相同,但可理解性较低,并且还执行其他一些操作,因此我选择不默认设置,因为它更容易理解您正在停止传播

As a brave editor says, you can also pass false as a third argument to the addEventListener and it does basically the same thing but is less comprehensible and does some additional things as well, so I have opted not to default to this just because its easier to understand that you are stopping propagation.

这篇关于停止点击事件传播的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆