css - 悬停时选择同级元素

标签 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>

最佳答案

遗憾的是,CSS 中没有“前一个兄弟”选择器(参见 complete list)。

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

你需要在这个上使用 JavaScript。

关于css - 悬停时选择同级元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49987285/

相关文章:

javascript - 如何使用vue-scroll

css - Bootstrap 中的嵌套网格系统

jQuery Mega 菜单闪烁问题

javascript - 使用 JQuery 或 CSS 如何在悬停时缓慢更改框的颜色?

html - 将鼠标悬停在链接上时使图像出现在背景中

css 不工作背景悬停事件 - 不是语法问题

html - 打开 DevTools 时,Electron BrowserWindow 切换到暗模式

javascript - Slider 范围的 HTML DOM 样式 backgroundImage 属性

javascript - 悬停在 jquery 中无法正常工作

html - 图片链接在悬停时闪闪发光