CSS选择器问题:悬停.behance类时无法选中目标元素怎么办
悬停.behance元素时无法选中.gauche-haut的原因与解决办法
问题描述
我希望在悬停.behance类元素时,选中.colonne-gauche下的.gauche-haut元素。HTML结构如下:
<body> <article> <h1 class="test">lorem<a href="#" class="behance"> portfolio</a></h1> </article> <div id="animation-2d"> <div class="grille"> <div class="colonne-gauche"> <div class="gauche-haut"></div> </div> </div> </div> </body>
使用article:hover ~ #animation-2d .gauche-haut { background-color: yellow; }可实现目标元素背景变黄,但改用article .behance:hover ~ #animation-2d .gauche-haut { background-color: yellow; }却无效,请问原因及解决办法?
原因分析
CSS的~(通用兄弟选择器)只能选中当前元素之后的同级兄弟元素,你的写法存在逻辑错误:
.behance是article内部h1的子元素,它的同级元素仅局限于h1内部的节点,和#animation-2d并非同级关系- 当你写
article .behance:hover ~ #animation-2d时,~试图匹配.behance的同级兄弟,但#animation-2d是article的同级,不是.behance的,所以这个选择器无法匹配到任何元素
而article:hover ~ #animation-2d能生效,是因为article和#animation-2d是同级兄弟,~可以正确关联两者。
解决办法
方法1:纯CSS(利用:has()选择器)
通过:has()选择器检测article内部是否有悬停的.behance元素,再关联同级的#animation-2d:
article:has(.behance:hover) ~ #animation-2d .gauche-haut { background-color: yellow; }
:has()是CSS选择器的新特性,目前Chrome、Firefox 121+、Safari 15.4+等主流浏览器均支持。
方法2:JavaScript实现(兼容旧浏览器)
如果需要兼容不支持:has()的旧浏览器,用JS监听鼠标事件来控制样式:
const behanceEl = document.querySelector('.behance'); const targetEl = document.querySelector('#animation-2d .gauche-haut'); behanceEl.addEventListener('mouseenter', () => { targetEl.style.backgroundColor = 'yellow'; }); behanceEl.addEventListener('mouseleave', () => { targetEl.style.backgroundColor = ''; });
内容的提问来源于stack exchange,提问作者Geoffrey Menissier
相关产品推荐
相关产品推荐

