在悬停时选择兄弟元素

时间:2018-04-23 18:00:11

标签: css hover

目标:

  • 当鼠标悬停在.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>

1 个答案:

答案 0 :(得分:1)

可悲的是,CSS中没有“上一个兄弟”选择器(参见complete list)。

请注意,可以使用 Flexbox order属性来模拟之前的兄弟选择,但之后无法应用下一个兄弟选择。

你需要在这个上使用JavaScript。

相关问题