两个:has选择器仅一个生效,如何在Chrome 106中激活两者?
解决两个
:has选择器无法同时生效的问题 问题场景
当页面中存在两个针对同一父元素的:has选择器时,仅能激活其中一个。注释第一个选择器后,第二个可正常运行;但同时启用时,第二个选择器失效。该问题在Chrome 106版本中复现。
原始代码
HTML代码
<div id="container"> <button class="to-mode-x">Mode X</button> <div> <div class="arrow material-icons">keyboard_double_arrow_down</div> <div class="arrow material-icons">keyboard_double_arrow_up</div> </div> <button class="to-mode-y">MODE Y</button> </div>
CSS代码
.arrow { background-color: red; } #container:has(.to-mode-y:hover) .arrow:first-child { animation: flow_to_y 2s ease-in-out infinite alternate; } #container:has(.to-mode-x:hover) .arrow:last-child { animation: flow_to_x 2s ease-in-out infinite alternate; } @keyframes flow_to_y { 0% { background-position: 0 0; } 50% { opacity: 1; } 100% { background-position: 0 100%; } } @keyframes flow_to_x { 0% { background-position: 0 0; } 50% { opacity: 1; } 100% { background-position: 0 100%; } }
解决方法
方法1:改用兄弟选择器替代:has(兼容性更好)
Chrome 106版本的:has选择器存在多规则解析bug,可通过传统的相邻/通用兄弟选择器实现相同效果,避免依赖:has:
.arrow { background-color: red; } /* 鼠标悬停.to-mode-y时,第一个arrow执行动画 */ #container .to-mode-y:hover ~ div .arrow:first-child { animation: flow_to_y 2s ease-in-out infinite alternate; } /* 鼠标悬停.to-mode-x时,第二个arrow执行动画 */ #container .to-mode-x:hover + div .arrow:last-child { animation: flow_to_x 2s ease-in-out infinite alternate; } @keyframes flow_to_y { 0% { background-position: 0 0; } 50% { opacity: 1; } 100% { background-position: 0 100%; } } @keyframes flow_to_x { 0% { background-position: 0 0; } 50% { opacity: 1; } 100% { background-position: 0 100%; } }
方法2:升级Chrome版本
该:has选择器的bug在Chrome后续版本(如110+)中已被修复,升级浏览器到最新稳定版后,原始代码可正常运行两个:has规则。
内容的提问来源于stack exchange,提问作者Usagi Ito
相关产品推荐
相关产品推荐

