簡體   English   中英

如何防止特定 div 上出現 onClick

[英]How to prevent a onClick on a specific div

我正在嘗試使用這些簡單的用例構建一個簡單的對話框:

  • 當用戶點擊黑色背景時,用戶應該關閉對話框(現在只是 window.alert)
  • 當用戶單擊白色 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM