简体   繁体   English

避免可悬停内容的单击事件触发父元素的单击事件

[英]Avoid that click event for hoverable content triggering event click for parent element

If I have a layout like this:如果我有这样的布局:

html html

    <div class="container" onclick="alert('clicked in the container');">
     <img src="notebook.jpg" alt="Notebook" style="width:100%;">
     <div class="content">
       <button type="button" name="button" onclick="action(event, this);">test1</button> <button type="button" name="button" style="float: right;" onclick="action(event, this);">test2</button>
     </div>
   </div>

   <script type="text/javascript">
     function action(evt, elem) {
       evt.preventDefault();
       alert('clicked in '+elem.innerText);
     }
   </script>

css css

.container {
  position: relative;
  max-width: 800px; /* Maximum width */
  margin: 0 auto; /* Center it */
}

.container:hover .content {
  display: block;
}

.container .content {
  position: absolute; /* Position the background text */
  bottom: 0; /* At the bottom. Use top:0 to append it to the top */
  background: rgb(0, 0, 0); /* Fallback color */
  background: rgba(0, 0, 0, 0.5); /* Black background with 0.5 opacity */
  color: #f1f1f1; /* Grey text */
  width: 100%; /* Full width */
  padding: 20px; /* Some padding */
  display: none;
}

what I can do for, when I click on any of the button inside the hoverable .content div, the event click for the parent element do not being triggered?我可以做什么,当我单击可悬停的.content div 内的任何按钮时,不会触发父元素的事件单击? Right now, when I do that, 2 alerts are displayed, showing the messages "click in test x" followed by "clicked in the container".现在,当我这样做时,会显示 2 个警报,显示消息“单击测试 x”,然后显示“单击容器”。

You should stop the event propagation (bubbling), hence your parent component will not fire您应该停止事件传播(冒泡),因此您的父组件不会触发

Altough, you should get rid of prevenDefault you don't need it无论如何,你应该摆脱 prevenDefault 你不需要它

<script type="text/javascript">
         function action(evt, elem) {
           evt.preventDefault();
           evt.stopPropagation();
           evt.stopImmediatePropagation();
           alert('clicked in '+elem.innerText);
         }
</script>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM