我有 4 个 div (.box),它们是一个父 div (.cont) 的子元素
CSS
.cont{
width: 100%;
height: auto;
}
.box{
width: 25%;
color: #fff;
text-align: center;
padding: 50px 0;
background: #333;
float: left;
}
HTML
<div class="cont">
<div class="box">
aaa
</div>
<div class="box">
aaa
</div>
<div class="box">
aaa
</div>
<div class="box">
aaa
</div>
</div>
我想做的是:当我悬停任何一个 child 时,所有其他 child 都应该改变。
首先我尝试了这个方法:
.box:nth-child(1):hover .box:not(:nth-child(1)) {
background:#ccc;
}
但我不能使用它,因为框不是框的父元素,它们是同一级别的元素。
然后我尝试使用同级选择器:
.box:nth-child(1):hover ~ .box:not(:nth-child(1)) {
background:#ccc;
}
.box:nth-child(2):hover ~ .box:not(:nth-child(2)) {
background:#ccc;
}
.box:nth-child(3):hover ~ .box:not(:nth-child(3)) {
background:#ccc;
}
.box:nth-child(4):hover ~ .box:not(:nth-child(4)) {
background:#ccc;
}
但问题是 sibling 选择器只适用于下一个 sibling (下一个 child ),在我的例子中一切都完美地工作 .box:nth-child(1):hover 所有其他的都在改变背景。但是对于 .box:nth-child(2):hover 只有 3 和 4 改变了样式,因为没有之前的兄弟选择器,所以 3 和 4 的结果相同。
有没有办法只用 CSS 或我必须使用 jQuery 来做到这一点?
最佳答案
.cont:hover > * {
background:#ccc; // make all childern of .cont #ccc
}
.cont:hover > *:hover {
background:#333; // revert the hovered child to #333
}
或者更简单:
/* selects all children of the hovered element that are not hovered theselves */
.cont:hover > *:not(:hover) {
background:#ccc;
}
关于jquery - 悬停第 nth-child(1) 时更改其他 child ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28885144/