悬停在div上会影响外部元素



当DIV徘徊时,我正在尝试影响外部元素。这样的东西:

<div class="affected">
  Hi
</div>
<div>
  <div class="hover-me"></div>
</div>

CSS:

.hover-me:hover ~ .affected {
  color: 
}

我已经尝试了其他同级选择器,但它不起作用。

带有纯CSS,它将变得像它一样棘手。

一种方法,如果您不需要包含悬停子的Div上的指针 - 悬停,点击,单击等(将容器设置为可操作的Div,请使用div,禁用指针evesents,将它们重置在孩子身上,并使用某种魔术在您的HTML上以相反的顺序使兄弟姐妹以兄弟姐妹的选择来定位(因为您不能瞄准以前的兄弟姐妹(

之类的东西

body{
  /*switches the oder of .affected and .hover-container, so .affected can be bellow in the HTML and be targeted with sibling selectors, while showing above*/
  display:flex;
  flex-direction:column-reverse;
}
.hover-container:hover ~ .affected{
/*targets the action on the container*/
  background:red;
}
.hover-container{
/*disables pointer-events on the container, so entering it won't cause the hover effect on the sibling*/
  pointer-events:none;
}
.hover-me{
/*resets pointer-events on the .hover-me child, so the previous :hover we set for the container will work only when hovering this child*/
  pointer-events:auto;
  cursor:pointer;
}
div{
  border:2px solid grey;
  margin:20px 40px;
  text-align:center;
}
<div class="hover-container">
  this is the hover container
  <div class="hover-me">hover me</div>
</div>
<div class="affected">
  affected
</div>

但这可能不是一个常见的情况,那时您会更好地使用JS方法。

最新更新