我有一個帶有點擊事件的元素和一個帶有另一個點擊事件的子元素。我做了以下解決方案,以防止在您單擊子元素時發生父操作
const parent = document.getElementById("parent")
parent.addEventListener("click", e =>{
alert("clicked")
})
const child = document.getElementById("child")
function prevent(e)
{
e.stopPropagation()
e.preventDefault()
}
child.addEventListener("click", prevent)
child.addEventListener("mousedown", prevent)
#parent{
width:300px;
height:300px;
background-color:yellow;
display: flex;
justify-content: center;
align-items: center;
}
#child{
width:100px;
height:100px;
background-color:red;
}
<div id="parent">
<div id="child">
</div>
</div>
但是,當您按住子元素中的按鈕并在父元素中釋放點擊時,有沒有辦法防止這種情況發生?
uj5u.com熱心網友回復:
這非常棘手(或者我遺漏了一些明顯的東西)。
下面通過記住最后一次 mousedown 來處理它(以一種不太可能被其他處理程式繞過的方式),然后如果 mousedown 通過子級傳遞,則忽略父級上的單擊事件。
let lastMouseDown = null;
// Use a capture handler on mousedown to remember that
// mousedown event (a capture handler so we see the event
// even if something stops propagation -- unless somebody
// registered a capture handler before us and stopped
// immediate propagation, which isn't all that likely
document.addEventListener(
"mousedown",
event => {
lastMouseDown = event;
},
true // A capture handler
);
const parent = document.getElementById("parent");
parent.addEventListener("click", e => {
// If the last mousedown event passed through the
// child, ignore this click
if (lastMouseDown && child.contains(lastMouseDown.target)) {
prevent(e);
return;
}
console.log("clicked");
});
const child = document.getElementById("child");
function prevent(e) {
e.stopPropagation();
e.preventDefault();
}
child.addEventListener("click", prevent);
child.addEventListener("mousedown", prevent);
#parent{
width:300px;
height:300px;
background-color:yellow;
display: flex;
justify-content: center;
align-items: center;
}
#child{
width:100px;
height:100px;
background-color:red;
}
<div id="parent">
<div id="child">
</div>
</div>
它在這個例子中有效,但我不能說我對它很滿意。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/470106.html
標籤:javascript