在我的窗口事件中,如果指针单击父项或其子项/后代,则它应该执行某些操作。
问题是该事件无法访问父母的孩子和孙子。条件存储在targetIsInsideParent
变量中。
HTML
<div class="parent">
Parent
<div class="child">
Child
<div class="grandchild">
GrandChild
</div>
</div>
</div>
JS
const parent = document.querySelector('.parent');
window.addEventListener('click', e => {
const targetIsParent = e.target === parent;
const targetIsInsideParent = e.target === parent.children; // !!!!
if(targetIsParent || targetIsInsideParent) {
console.log('Good');
}
})
答案 0 :(得分:1)
尝试使用parent.contains(e.target)
或parent.compareDocumentPosition(e.target) === 20
const parent = document.querySelector('.parent');
window.addEventListener('click', e => {
const targetIsParent = e.target === parent;
const targetIsInsideParent = parent.contains(e.target);
// const targetIsInsideParent = parent.compareDocumentPosition(e.target) === 20; // alternative, but also works good
if(targetIsParent || targetIsInsideParent) {
console.log('Good');
}
})
<div class="parent">
Parent
<div class="child">
Child
<div class="grandchild">
GrandChild
</div>
</div>
</div>
<div>Other</div>