如何禁用div内特定子元素触发的父容器hover效果
问题描述
我想要实现如下hover效果:


核心需求为:当hover父容器内的特定子元素时,阻止父容器的白色区域变暗。
现有HTML代码
<div className= {css.searchBarDiv}> <div className={css.searchBarContent}/> <div className={css.searchBarButton}> <div className={css.button}> <Image/> </div> </div> </div>
现有CSS代码(SCSS写法)
.searchBarDiv { &:hover { background-color: #e7e7e7; } &:focus-within { background-color: #ffffff; box-shadow: rgb(0 0 0 / 20%) 0px 6px 20px; } } .searchBarButton { flex: 0 0 auto; margin-left: -6px; padding-right: 9px; align-self: center; } .button { max-width: 200px; animation-delay: 0.8s; background-color: #ee3465; color: #ffffff; cursor: pointer; &:hover { text-decoration: none; color: #ffffff; background-color: #df3562; } }
解决方案
你可以用CSS的:has()选择器来排除hover到按钮时的父容器变暗逻辑,直接修改.searchBarDiv的hover规则即可:
.searchBarDiv { /* 仅hover非按钮区域时才触发父容器变暗 */ &:hover:not(:has(.button:hover)) { background-color: #e7e7e7; } &:focus-within { background-color: #ffffff; box-shadow: rgb(0 0 0 / 20%) 0px 6px 20px; } /* 其余原有规则保持不变 */ }
如果需要兼容不支持:has()的旧浏览器,可以改用JS监听事件实现:
const searchBar = document.querySelector(`.${css.searchBarDiv}`) const button = document.querySelector(`.${css.button}`) button.addEventListener('mouseenter', () => { searchBar.classList.add('button-hovering') }) button.addEventListener('mouseleave', () => { searchBar.classList.remove('button-hovering') })
对应修改CSS hover规则:
.searchBarDiv { &:hover:not(.button-hovering) { background-color: #e7e7e7; } /* 其余原有规则保持不变 */ }
内容的提问来源于stack exchange,提问作者Laveen Ren
相关产品推荐
相关产品推荐

