我有这个html代码:
<div class="container">
<div class="parent">
<!-- P Element Completely On Parent -->
<p style="width: 100%; height: 100%;">Hello</p>
</div>
........
</div>
这是我的Javascript:
document.querySelector(".container").addEventListener("click", (e) => {
if ( e.target == document.querySelector(".parent") ) {
alert(" It Worked!!! ")
}
},
true // <--- bubbling
)
style="pointer-events: none"
)
是否可以检测到父元素单击而不给出事件(和事件冒泡)?结果代码应该在客户端单击p element
后工作
发布于 2020-07-23 08:31:59
如果.parent
的嵌套是动态的,您可能需要确定从currentTarget
到target
的路径。然后在路径中搜索您要寻找的特定元素。
// Determines the node path from baseNode to targetNode, by travelling up from
// the targetNode. The retuned array will include both the baseNode and the
// targetNode. If the targetNode is the baseNode an array with one elment is
// returned. Throws an error if baseNode is not an ancestor of targetNode.
function nodePath(baseNode, targetNode, currentPath = []) {
currentPath.unshift(targetNode);
if (targetNode == baseNode) return currentPath;
return nodePath(baseNode, targetNode.parentNode, currentPath);
}
document
.querySelector(".container")
.addEventListener("click", ({currentTarget, target}) => {
const path = nodePath(currentTarget, target);
const parent = path.find(node => node.matches(".parent"));
if (parent) {
console.log("It Worked!");
}
});
<div class="container">
<div class="parent">
<!-- P Element Completely On Parent -->
<p style="width: 100%; height: 100%;">Hello</p>
</div>
........
</div>
发布于 2020-07-23 01:51:33
是的,你可以试试这个。
document.querySelector(".container").addEventListener("click", (e) => {
var parentel = e.target.parentElement
if (parentel.className == "parent") {
alert(" It Worked!!! ")
}
})
<div class="container">
<div class="parent">
<!-- P Element Completely On Parent -->
<p class- "child" style="width: 100%; height: 100%;">Hello</p>
</div>
</div>
https://stackoverflow.com/questions/63045456
复制相似问题