目标:
- 当悬停在
.one
上时,我希望.two
和.three
都使用 相同的 BG 图片。 - 当悬停在
.two
上时,我希望.one
和.three
都使用 相同的 BG 图片。 - 当悬停在
.three
上时,我希望.one
和.two
都使用
相同的 BG 图片。
兄弟选择器似乎不允许 :hover
上的先前兄弟元素。有解决办法吗?
.item{
width: 200px;
height: 200px;
float: left;
margin: 15px;
cursor: pointer;
transition: all .3s ease;
}
.one,
.one:hover ~ .two,
.one:hover ~ .three{
background: url('https://placeimg.com/200/200/nature');
}
.two,
.two:hover ~ .one,
.two:hover ~ .three{
background: url('https://placeimg.com/200/200/arch');
}
.three,
.three:hover ~ .one,
.three:hover ~ .two{
background: url('https://placeimg.com/200/200/tech');
}
<div class="item one"></div>
<div class="item two"></div>
<div class="item three"></div>
更新:看起来没有针对此的 CSS 解决方案,但我确实创建了一个 jQuery 解决方案。
$('.one').hover(
function(){ $('.two, .three').addClass('one-all') },
function(){ $('.two, .three').removeClass('one-all') }
);
$('.two').hover(
function(){ $('.one, .three').addClass('two-all') },
function(){ $('.one, .three').removeClass('two-all') }
);
$('.three').hover(
function(){ $('.one, .two').addClass('three-all') },
function(){ $('.one, .two').removeClass('three-all') }
);
.item{
width: 200px;
height: 200px;
float: left;
cursor: pointer;
transition: all .3s ease;
}
/* original images */
.one{ background: url('https://placeimg.com/200/200/nature');}
.two{ background: url('https://placeimg.com/200/200/arch');}
.three{ background: url('https://placeimg.com/200/200/tech');}
/* replacement images*/
.one-all{ background: url('https://placeimg.com/200/200/nature');}
.two-all{ background: url('https://placeimg.com/200/200/arch');}
.three-all{ background: url('https://placeimg.com/200/200/tech');}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="item one"></div>
<div class="item two"></div>
<div class="item three"></div>
最佳答案
遗憾的是,CSS 中没有“前一个兄弟”选择器(参见 complete list)。
请注意,可以使用 Flexbox order
属性来模拟 previous sibling 选择,但此后无法应用下一个兄弟选择。
你需要在这个上使用 JavaScript。
关于css - 悬停时选择同级元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49987285/