[英]How to prevent a onClick on a specific div
我正在嘗試使用這些簡單的用例構建一個簡單的對話框:
我的問題:當用戶單擊白色 div 中的任何點時,function 被觸發,而我希望所有白色 div 都不響應點擊。
任何想法如何解決它? CSS 或 JS 解決方案欣賞
const parent = document.getElementById('parent') const child = document.getElementById('child') const button = document.getElementById('button') parent.addEventListener('click', () => window.alert('close')) button.addEventListener('click', (e) => { e.stopPropagation() window.alert('do something else')} )
.parent { position: absolute; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; background-color: gray; }.child { width: 200px; height: 200px; background-color: white; }
<div id="parent" class="parent"> <div id="child" class="child"> some content <button id="button">do something else</button> </div> </div>
事件“冒泡”。 所以假設你的意思是說
const child = document.getElementById('child')
你可以取消冒泡。
child.addEventListener('click', e => e.stopPropagation())
使用事件委托:
document.addEventListener('click', (evt) => { const origin = evt.target; console.clear(); // only do something if the origin clicked // is #parent or #button if (origin.id === "parent") { return console.log('close'); } if (origin.id === "button") { return console.log("something else"); } });
.parent { position: absolute; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; background-color: gray; }.child { width: 200px; height: 200px; background-color: white; }
<div id="parent" class="parent"> <div id="child" class="child"> some content <button id="button">do something else</button> </div> </div>
只需添加此代碼
child.addEventListener('click', (e)=> {
e.stopImmediatePropagation();
});
const parent = document.getElementById('parent') const child = document.getElementById('child') const button = document.getElementById('button') parent.addEventListener('click', () => window.alert('close')) button.addEventListener('click', (e) => { e.stopPropagation() window.alert('do something else')} ) child.addEventListener('click', (e)=> { e.stopImmediatePropagation(); });
.parent { position: absolute; display: flex; align-items: center; justify-content: center; width: 100%; height: 100%; background-color: gray; }.child { width: 200px; height: 200px; background-color: white; }
<div id="parent" class="parent"> <div id="child" class="child"> some content <button id="button">do something else</button> </div> </div>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.