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

div元素hover属性失效:悬停圆形元素无法切换背景与文本

问题原因分析

1. 最初选择器失效的核心原因

你写的 div.red:hover div.bg 是后代选择器,它仅能匹配 div.red 内部的子元素 div.bg。但你的DOM结构里,.bg 是和 .red、.green 等圆形div同级的兄弟元素,并非子元素,所以这个选择器根本找不到目标元素,hover自然不会产生任何效果。

2. 部分文本opacity未生效的原因

你第一版代码里,仅给红、绿、蓝三种颜色对应的p元素写了hover时的opacity切换规则,漏掉了橙色的:

/* 缺失的关键代码 */
div.orange:hover ~ div.bg p.orange {
  opacity: 1;
}

另外补充说明:兄弟选择器 ~ 的特性是仅能选中当前元素之后的同级兄弟,你的DOM结构里.bg确实在所有圆形div之后,所以div.red:hover ~ div.bg这类选择器是有效的;如果后续调整DOM把.bg放到圆形div前面,这个选择器就会直接失效。

额外细节问题

你CSS里写的 font-weight: arial 是错误用法:font-weight 控制字体粗细,设置字体应该用 font-family: arial。


修正后的完整代码

CSS 部分

* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

/* 圆形按钮样式 */
div.red {
  background-color: #f00;
  top: 20px;
  left: 20px;
}

div.green {
  background-color: rgb(44, 150, 2);
  top: 20px;
  right: 20px;
}

div.blue {
  background-color: #020496;
  bottom: 20px;
  left: 20px;
}

div.orange {
  background-color: #f09308;
  bottom: 20px;
  right: 20px;
}

div.circle {
  position: fixed;
  height: 34px;
  width: 34px;
  border-radius: 50%; /* 用50%实现圆形更标准 */
  border: 2px solid white;
  cursor: pointer;
  z-index: 10; /* 确保圆形在背景层上方,避免被遮挡 */
}

/* 背景层样式 */
div.bg {
  height: 100vh;
  background-color: #ddd;
  transition: background-color 1s;
}

.bg p {
  text-align: center;
  line-height: 100vh;
  width: 100%;
  font-size: 50px;
  font-family: arial; /* 修正字体属性错误 */
  color: white;
  opacity: 0;
  transition: opacity 1s; /* 给文本添加过渡动画 */
  position: absolute; /* 让所有文本元素重叠在同一位置 */
  top: 0;
  left: 0;
}

/* 背景色切换规则 */
div.red:hover ~ div.bg {
  background-color: red;
}
div.green:hover ~ div.bg {
  background-color: rgb(5, 105, 5);
}
div.blue:hover ~ div.bg {
  background-color: rgb(0, 32, 175);
}
div.orange:hover ~ div.bg {
  background-color: orange;
}

/* 文本显示规则 */
div.red:hover ~ div.bg p.red {
  opacity: 1;
}
div.green:hover ~ div.bg p.green {
  opacity: 1;
}
div.blue:hover ~ div.bg p.blue {
  opacity: 1;
}
div.orange:hover ~ div.bg p.orange {
  opacity: 1;
}

HTML 部分

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="ie=edge" />
  <title>悬停切换背景色</title>
  <link rel="stylesheet" href="style.css" />
</head>

<body>
  <div class="red circle"></div>
  <div class="green circle"></div>
  <div class="blue circle"></div>
  <div class="orange circle"></div>
  <div class="bg">
    <p class="red">红色</p>
    <p class="green">绿色</p>
    <p class="blue">蓝色</p>
    <p class="orange">橙色</p>
  </div>
</body>
</html>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.21 13:16:15