当鼠标悬停在另一个元素上时,更改元素的属性

3

我有两个div,我想通过悬停在第二个div上来改变第一个div的颜色。我找到了一些解决方案,当“hovered”出现在要更改其CSS的目标之前时,但如果“hovered”出现在之后呢?有什么方法可以不使用JavaScript来实现吗?

.box, .box-2 {
  display: block;
  height: 100px;
  width: 100px;
  margin: 20px;
}

.box {
  background-color: red;
}

.box-2 {
  background-color: blue;
}

.box-2:hover + .box {
  background-color: green;
}
<body>
<div class="wrapper"> 
  <div class="box"></div>
  <div class="box-2"></div>
</div>
</body>

2个回答

3

一种解决方法是在视觉上反转顺序,同时保留DOM中的顺序,这样您仍然可以使用+选择器。

以下是使用flexbox的示例:

.wrapper {
  display:flex;
  flex-direction:column;
}

.box, .box-2 {
  display: block;
  height: 100px;
  width: 100px;
  margin: 20px;
}

.box {
  background-color: red;
}

.box-2 {
  background-color: blue;
  order:2; /* this will make box-2 goes after */
}

.box-2:hover + .box {
  background-color: green;
}
<body>
<div class="wrapper"> 
  <div class="box-2"></div>
  <div class="box"></div>
</div>
</body>


一些相关问题,以获取更多想法:

是否存在“前一个兄弟”CSS选择器?

前一个相邻兄弟选择器的解决方法?


1

虽然Temani的回答是一个很好的技巧,但如果你需要双向工作,则我有一些建议,可以使用:not()选择器,尽管由于边距的原因,这种方法有点不太可靠。

如果您检查对.wrapper元素的悬停状态,那么当它没有悬停时,您就可以为您的框添加样式,如下所示:

.wrapper:hover > .box:not(:hover) {
    background-color: green;
}

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