如何避免子元素绝对定位为触发父点击处理程序?
如果我单击div
,它将触发clickMe()
。
<div onclick="clickMe()" style="height: 1600px; background: blue;">
<div> Test </div>
</div>
function clickMe() {
console.log("CLICK ME CLICKED")
}
防止传播的唯一方法是在div
上使用点击处理程序来停止传播吗?
<div onclick="clickMe()" style="height: 1600px; background: blue;">
<div onclick="buttonClicked()"> Test </div>
</div>
function clickMe() {
console.log("CLICK ME CLICKED")
}
function buttonClicked() {
event.stopPropagation();
}
您使用的是内联事件属性(onclick
(和全局event
对象,这是一种已有20多年历史的技术,现在不应该使用。将.addEventListener()
与HTML分开使用,并将事件处理函数设置为将event
作为参数(因为所有DOM事件处理程序都会自动传递到事件激发时创建的event
对象的引用(。然后,在处理程序中检查event.target
,以确保只有在正确的元素触发事件时才执行操作。
事实上,在许多情况下,您不需要像现在这样在嵌套项上设置多个事件处理程序,然后处理传播,只需在祖先元素上设置一个事件处理器,就可以让冒泡发生,并根据event.target
决定如何进行。这被称为";事件委托";。
您还应该努力避免内联样式,而是使用CSS类来应用样式。
// Set your events up in JavaScript, not with
// inline HTML event attributes
document.addEventListener("click", function(evt){
// Check to see if the desired element was the
// source of the event
if(evt.target.classList.contains("clickMe")){
// Perform the appropriate actions for this element
console.log("CLICK ME CLICKED");
}
});
.clickMe {
height: 1600px;
background: blue;
color:yellow;
}
<div class="clickMe">
<div> Test </div>
</div>