CSS触发器仅悬停在顶部元素上

时间:2015-03-02 16:20:46

标签: css css3

是否有优雅的解决方案只悬停顶级元素,而不是底层;或者我应该使用javascript做到这一点?

<div class="WithHover1">
   <div class="WithHover2">
       I am Top and I want to be the only div hightlighted
   </div>
   I want to be hightlighted too, but I dont want to be hightlighted when the nested one is
</div>

3 个答案:

答案 0 :(得分:3)

你不能只用CSS做到这一点。选择器处于草案中,用于4/5级(我忘了)CSS选择器,这将是非常棒的。

目前,javascript / jquery将是最简单,最实用的方法。

$(".WithHover2").mouseover(function() {
    $(".WithHover1").removeClass("highlight");
    $(this).addClass("highlight");
});

答案 1 :(得分:2)

这是一个CSS3解决方案,使用::after伪元素,底部边框覆盖底部文本的背景颜色。

否定z-index会阻止边框覆盖文字,overflow: hidden会阻止WithHover1因大边框而展开。

适用于IE11(至少),Chrome,Firefox,Safari和Opera:

div.WithHover1 {
  font: 14px verdana;
  position: relative;
  overflow: hidden;
}

div.WithHover1:hover {
  background: yellow;
  position: relative;
  z-index: 1;
}

div.WithHover2:hover {
  background: orange;
}

div.WithHover2:hover::after {
  content: '';
  display: block;
  position: absolute;
  border-bottom: 1000px solid white;
  width: 100%;
  z-index: -1;
}
<div class="WithHover1">
  <div class="WithHover2">
    I am Top and I want to be the only div highlighted
  </div>
  I want to be highlighted too, but I dont want to be highlighted when the nested one is.
  Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum
</div>

答案 2 :(得分:-1)

这不是你想要的吗?你的帖子对我来说并不清楚你在悬停在每个帖子上时需要什么。

&#13;
&#13;
.WithHover2:hover, .WithHover3:hover {
    background-color: yellow;
}
&#13;
<div class="WithHover1">
   <div class="WithHover2">
       I want to be the only div hightlighted
   </div>
   <div class="WithHover3">
       I dont want to be hightlighted when the nested one is
   </div>
</div>
&#13;
&#13;
&#13;