gpt4 book ai didi

javascript - 忽略 div 内的所有事件

转载 作者:行者123 更新时间:2023-12-01 02:27:49 25 4
gpt4 key购买 nike

假设我有这个 div:

let div = document.createElement('div');
div.id = 'foobar';
div.innerHTML = '<button>foo</button>';
document.body.insertBefore(div, document.body.firstChild);

我也用

 window.addEventListener('click', function(event){
// I want to ignore any events
// originating from within the div with id = 'foobar'
});

如评论中所述,我想忽略源自 id = 'foobar' 的 div 内的任何事件,我该怎么做?

最佳答案

使用Node.prototype.contains,这似乎有效:

window.addEventListener('click', function (ev) {

if (ev.target == div) {
console.log('we can ignore this event...because its from the modal.');
return;
}


let contains = div.contains(ev.target);
if (contains) {
console.log('we can ignore this event...because its from a child in the modal.');
return;
}

});

关于javascript - 忽略 div 内的所有事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48603630/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com