CSS仅对顶部元素触发悬停效果

3

有没有优雅的解决方案只对顶部元素进行hover,而不是底层元素;或者我应该使用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>

1
你能澄清一下什么是“top”元素吗?目前它的含义不太明确。 - peterdotjs
为什么不将“bottom”文本包装在另一个元素中呢?请查看下面的答案。 - mellis481
3个回答

3
你不能仅使用CSS来实现这个功能。has选择器当前处于4/5级别的草案中,一旦发布将非常强大。
目前,使用JavaScript/jQuery是最简单、最实用的方法。
$(".WithHover2").mouseover(function() {
    $(".WithHover1").removeClass("highlight");
    $(this).addClass("highlight");
});

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>


-1

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

.WithHover2:hover, .WithHover3:hover {
    background-color: yellow;
}
<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>


我无法确定他是否要求这个,我认为可能是,但我无法确定他是否希望它们成为可互换的亮点,但嵌套的将具有优先权。 - Jack hardcastle
顶部元素是 div.WithHover1 - Knut Holm
1
这个问题如此含糊不清,可为什么会有人给它投反对票呢? - mellis481
@im1dermike,你的解决方案突出了div.WithHover2,但它不是顶层元素...你没有回答问题。 - Knut Holm
1
@Akarienta:我认为作者没有必要通过不改变HTML来使他们想要做的事情变得复杂化。我更新了我的片段,以展示我认为他们想要做的事情。 - mellis481
显示剩余2条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接