我试图在 div 悬停时影响外部元素。像这样的事情:
<div class="affected">
Hi
</div>
<div>
<div class="hover-me"></div>
</div>
CSS:
.hover-me:hover ~ .affected {
color:
}
我尝试过其他同级选择器,但它不起作用。
对于纯 CSS,这将是非常棘手的。
一种方法,IF您不需要在包含可悬停子项的 div 上使用指针事件(悬停、单击等),请将容器设置为可操作的 div,禁用指针事件,在子项上重置它们,并使用某种魔法来在 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 方法会更好。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)