You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现鼠标悬停square元素时改变square2元素的颜色?

实现鼠标悬停触发兄弟元素颜色变化

CSS方案(优先推荐)

先修正你原代码里的几个问题:

  • 类选择器必须加前缀.,比如.square而非square
  • CSS背景色属性是background-color,不是background_color
  • 要选中目标兄弟元素,需使用兄弟选择器

情况1:两个div是相邻兄弟(中间无其他元素)

使用相邻兄弟选择器+,仅选中紧随其后的第一个兄弟元素:

/* 给square2设置默认绿色背景 */
.square2 {
  background-color: #00ff00;
  transition: background-color 0.3s; /* 可选:添加过渡动画让颜色变化更平滑 */
}

/* 悬停.square时,修改相邻.square2的背景色 */
.square:hover + .square2 {
  background-color: #ff0000;
}

情况2:两个div之间有其他元素

使用通用兄弟选择器~,会选中所有后续的同层级兄弟元素:

.square2 {
  background-color: #00ff00;
  transition: background-color 0.3s;
}

.square:hover ~ .square2 {
  background-color: #ff0000;
}

对应的HTML保持你的结构即可:

<div class="square">
  <p class="square1_text">~66.6%</p>
</div>

<!-- 情况2下,此处可插入其他元素 -->
<!-- <div>其他内容</div> -->

<div class="square2">
  <p class="square2_text">~33.3%</p>
</div>

JavaScript方案(CSS选择器无法满足场景时使用)

如果两个元素不在同一父容器下,或有更复杂的交互逻辑,可通过JS监听鼠标事件实现:

const square = document.querySelector('.square');
const square2 = document.querySelector('.square2');

// 鼠标悬停时切换为红色
square.addEventListener('mouseover', () => {
  square2.style.backgroundColor = '#ff0000';
});

// 鼠标离开时恢复绿色
square.addEventListener('mouseout', () => {
  square2.style.backgroundColor = '#00ff00';
});

配套基础CSS和HTML:

.square2 {
  background-color: #00ff00;
  transition: background-color 0.3s;
}
<div class="square">
  <p class="square1_text">~66.6%</p>
</div>

<div class="square2">
  <p class="square2_text">~33.3%</p>
</div>

内容的提问来源于stack exchange,提问作者quinten

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.25 11:52:06