addEventListener 到除一个元素之外的所有元素 [英] addEventListener to all but one element

查看:28
本文介绍了addEventListener 到除一个元素之外的所有元素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试让自己远离 jQuery(我的心在正确的地方,不是吗?),但我无法获得与 :not() 选择器.

I'm trying to wean myself off jQuery (my heart is in the right place, no?), and I'm having trouble getting to what would be the equivalent of the :not() selector.

我有 document.body.addEventListener("mousewheel", scrollTriggered),我想在滚动除特定 div 之外的任何内容时触发它(在小提琴中,#something).我试过集成 event.target,但无济于事.

I have document.body.addEventListener("mousewheel", scrollTriggered), which I want to fire on scroll of anything but a specific div (in the fiddle, #something). I've tried integrating event.target, to no avail.

非常感谢任何帮助.参见 JSFiddle

Any help greatly appreciated. See JSFiddle

推荐答案

您可以检查事件是否源自您想要避免的元素内部.为此,您必须从 target 向上遍历 DOM 树并比较每个节点的 id 属性,或者使用 Node.contains(不过请先检查兼容性部分):

You can check whether the event originated from within the element you want to avoid. To do that, you have to traverse up the DOM tree from target and compare each Node's id attribute, or use Node.contains (check the compatibility section first though):

var ignore = document.getElementById('something');

function scrollTriggered(event) {
    var target = event.target;
    if (target === ignore || ignore.contains(target)) {
        return;
    }
    // do other stuff
}

演示

也就是说,Markasoftware 的答案更好,因为它首先阻止了事件.

That said, Markasoftware's answer is even better, since it prevents the event in the first place.

这篇关于addEventListener 到除一个元素之外的所有元素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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