React中添加前景DOM元素后CSS六边形动画失效求助
解决六边形悬停动画被前景元素遮挡的问题
问题根源分析
- React组件错误嵌套
<body>标签,破坏了正常DOM结构,导致层级关系混乱 - 六边形的
:before伪元素设置z-index:2,完全遮挡六边形本体,拦截了鼠标悬停事件 - 全局
isHover状态导致所有六边形同步变色,不符合单个悬停的预期 - z-index层级设置逻辑混乱,背景容器z-index过高,前景元素层级关系未正确匹配
修复步骤
- 移除组件内的
<body>标签,React组件应渲染在页面根<body>内部,而非嵌套 - 给
.hexagon添加position: relative,确保伪元素定位基准正确 - 给六边形的伪元素(
:before/:after)添加pointer-events: none,让鼠标事件穿透到六边形本体 - 删除全局
isHover状态,直接使用CSS原生:hover实现单个六边形的悬停效果 - 调整z-index层级:背景容器设为
z-index: -1作为底层背景,前景元素保持z-index:1即可
修改后的完整代码
React组件代码
import React from "react"; import './Background.css' const HexBG = () => { const rows = 15; const hexagonsPerRow = 20; return ( <div className="hexagon-container"> <div className="container"> {Array(rows).fill().map((_, rowIndex) => ( <div key={rowIndex} className="row"> {Array(hexagonsPerRow).fill().map((_, hexagonIndex) => ( <div key={`${rowIndex}-${hexagonIndex}`} className="hexagon" > </div> ))} </div> ))} </div> </div> ) } export default HexBG;
CSS代码
.hexagon-container { position: fixed; top: 0; left: 0; width: 100%; height: 100%; z-index: -1; /* 设为底层背景 */ pointer-events: auto; /* 确保能接收鼠标事件 */ } * { margin: 0; padding: 0; box-sizing: border-box; } body { background-color: black; } .row { display: inline-flex; margin-top: -32px; margin-left: -50px; } .row:nth-child(even) { margin-left: 2px; } .hexagon { position: relative; /* 为伪元素提供定位基准 */ width: 100px; height: 110px; margin: 2px; background-color: rgb(59, 57, 57); clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%); animation: animation 14s linear infinite; transition: background-color 0s; pointer-events: auto; } .hexagon:hover { background-color: rgb(0, 245, 20); } @keyframes animation { 0% { filter: hue-rotate(0deg); } 100% { filter: hue-rotate(360deg); } } .hexagon:after { content: ""; position: absolute; top: 4px; bottom: 4px; left: 4px; right: 4px; background-color: rgb(54, 53, 53); clip-path: polygon(50% 0%, 100% 25%, 100% 75%, 50% 100%, 0% 75%, 0% 25%); pointer-events: none; /* 禁止伪元素拦截鼠标事件 */ } .hexagon:before { content: ""; position: absolute; width: 50%; height: 100%; background-color: rgba(0, 0, 0, 0.3); z-index: 2; pointer-events: none; /* 禁止伪元素拦截鼠标事件 */ } .foreground-element { z-index: 1; /* 前景元素层级高于背景 */ position: relative; /* z-index需要配合定位生效 */ }
内容的提问来源于stack exchange,提问作者oz.vegas
相关产品推荐
相关产品推荐

