繁体   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