【问题标题】:Avoid that click event for hoverable content triggering event click for parent element避免可悬停内容的单击事件触发父元素的单击事件
【发布时间】:2020-04-26 19:46:47
【问题描述】:

如果我有这样的布局:

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

.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;
}

我可以做什么,当我单击可悬停的.content div 内的任何按钮时,不会触发父元素的事件单击?现在,当我这样做时,会显示 2 个警报,显示消息“单击测试 x”,然后显示“单击容器”。

【问题讨论】:

    标签: javascript html css


    【解决方案1】:

    您应该停止事件传播(冒泡),因此您的父组件不会触发

    不过,你应该去掉 prevenDefault 你不需要它

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-12-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-28
      • 1970-01-01
      相关资源
      最近更新 更多