求助:鼠标悬停元素时修改其他元素文本颜色的CSS实现方案
解决鼠标悬停子元素时修改父元素文本颜色的问题
你当前的CSS选择器写法有误,因为CSS原生无法通过子元素的hover状态直接选中父元素,所以.headingRestaurant:hover textb这条规则根本不会生效。下面给你两种可行的解决方案:
方案一:使用CSS :has()选择器(现代浏览器推荐)
利用:has()选择器可以检测父元素是否包含处于hover状态的子元素,从而修改父元素的样式:
/* 默认文本颜色,可根据你的页面需求调整 */ .textb { color: #333; } /* 当子元素.headingRestaurant被hover时,父元素.textb的文本变为白色 */ .textb:has(.headingRestaurant:hover) { color: white; } /* hover时"restaurant"文本变为红色 */ .headingRestaurant:hover { color: red; }
HTML代码保持不变:
<h1 class="textb">Not a <span id="heading1" class="headingRestaurant">restaurant</span>, <br> but here for them.</h1>
注意:
:has()选择器支持Chrome 105+、Firefox 121+、Safari 15.4+,如果需要兼容更老的浏览器,建议用下面的JavaScript方案。
方案二:JavaScript实现(兼容旧浏览器)
通过监听子元素的鼠标事件,给父元素和子元素添加/移除样式类:
/* 默认样式 */ .textb { color: #333; } /* 父元素激活时的样式 */ .textb.hover-active { color: white; } /* 子元素hover时的样式 */ .headingRestaurant.hover-red { color: red; }
<h1 class="textb">Not a <span id="heading1" class="headingRestaurant">restaurant</span>, <br> but here for them.</h1>
const restaurantSpan = document.querySelector('.headingRestaurant'); const textbElement = document.querySelector('.textb'); // 鼠标悬停时添加样式类 restaurantSpan.addEventListener('mouseover', () => { textbElement.classList.add('hover-active'); restaurantSpan.classList.add('hover-red'); }); // 鼠标离开时移除样式类 restaurantSpan.addEventListener('mouseout', () => { textbElement.classList.remove('hover-active'); restaurantSpan.classList.remove('hover-red'); });
内容的提问来源于stack exchange,提问作者Thor Solutions
相关产品推荐
相关产品推荐

