js实现判断点击自身以及自身父元素
` const isDescendant = (el, parent) => {//传入e.target,目标元素
//点击自身或自身父元素则返回true,否则false
let isChild = false
if (el.parentNode === parent) { //is this the element itself?
isChild = true
}
while (el = el.parentNode) {
if (el.parentNode == parent) {
isChild = true
}
}
return isChild
}
// 点击除自身外的任何地方都触发使用
window.addEventListener("mouseup", (e) => {
if (isDescendant(e.target, trash.value)) {
}
});
`
vue方式:
给父元素设置点击事件:点击隐藏; 给子元素设置@click.stop 这样就会在点子元素的时候不会冒泡,也就不会出发父元素的事件。可以实现点击父元素隐藏,不被子元素影响
进阶版:给父元素设置@click.self:只有事件源是自身的时候会触发: