简体   繁体   中英

Hover on child nested element should not effect parent

HTML for my page is like this. When I hover over the child, it triggers hover on the parent as well. I want only the child hover to be effective when I hover child. How can I achieve this? Prefer CSS solution but javascript addition is also fine

<div class="element">
  <span class="inv"> invisible1 </span>
  <span class="col1"> test </span>
  <div class="element"> 
    <span class="inv"> invisible2 </span>
    <span class="col2"> test child </span>
  </div>
</div>

CSS:

.inv{
  opacity: 0;
}
.element:hover > .inv{
  opacity: 100;
}

Simple answer: You cannot prevent hover to work on parent.

Long answer: The events always bubble up the dom tree unless stopped by javascript, but to CSS, the element will still be hovered on. The reason why is simply because since the child is inside the parent, hovering the child makes it obvious that you are hovering the parent too.

You can, however, change your markup to accommodate for what you would like.

 .inv { opacity: 0; } .item:hover>.inv { opacity: 100; } 
 <div class="element"> <div class="item"> <span class="inv"> invisible1 </span> <span class="col"> test </span> </div> <div class="element"> <div class="item"> <span class="inv"> invisible2 </span> <span class="col"> test child </span> </div> </div> </div> 

Here is a hacky solution that allow you to hover on the visible text to show the hidden one. The trick is to extend the hidden text with a pseudo element to capture the hover event.

It's a hacky solution because you need to specify a big value that may cover other elements (and probably other side effects)

 .inv { opacity:0; position:relative; } .inv:before { content:""; position:absolute; top:0; left:0; bottom:0; right:-200px; /*this need to be big to cover the visible text*/ } .inv:hover { opacity:1; } 
 <div class="element"> <span class="inv"> invisible1 </span> <span class="col1"> test </span> <div class="element"> <span class="inv"> invisible2 </span> <span class="col2"> test child </span> </div> </div> 

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