简体   繁体   中英

Avoid that click event for hoverable content triggering event click for parent element

If I have a layout like this:

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

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? Right now, when I do that, 2 alerts are displayed, showing the messages "click in test x" followed by "clicked in the container".

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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