CSS问题:鼠标悬停类及类::before时显示文本实现失败
问题分析与修复方案
核心问题
- CSS伪元素无法被JS获取:
::before是CSS生成的虚拟元素,不属于DOM节点,所以document.querySelector('.split-bottom-left::before')永远返回null,导致JS里的伪元素hover判断完全失效。 - hover范围与视觉区域不匹配:伪元素的
skew变形后,实际可触发hover的范围还是原元素的矩形区域,和视觉上的倾斜区域不符。 - 缺少背景模糊效果:原代码没有实现悬停时的背景模糊逻辑。
修复代码
HTML(移除冗余JS事件,改为结构化区域)
<div class="split-screen"> <div class="split-left"> <div class="area area-top-left"></div> <div class="area area-bottom-left"></div> <div class="content content-top-left"> <h2>Top Left</h2> </div> <div class="content content-bottom-left"> <h2>Bottom Left</h2> </div> </div> <div class="split-right"> <div class="area area-top-right"></div> <div class="area area-bottom-right"></div> <div class="content content-top-right"> <h2>Top Right</h2> </div> <div class="content content-bottom-right"> <h2>Bottom Right</h2> </div> </div> </div>
CSS(纯CSS实现hover效果,匹配视觉区域)
body { margin: 0; padding: 0; } .split-screen { display: flex; width: 100vw; height: 100vh; } .split-left, .split-right { flex: 1; position: relative; overflow: hidden; } .area { position: absolute; width: 100%; height: 100%; cursor: pointer; transition: all 0.5s; } /* 左上倾斜区域 */ .area-top-left { background-color: green; transform: skewY(-45deg); transform-origin: bottom right; height: 200%; top: -100%; } /* 左下矩形区域 */ .area-bottom-left { background-color: black; top: 50%; } /* 右上倾斜区域 */ .area-top-right { background-color: red; transform: skewY(45deg); transform-origin: bottom left; height: 200%; top: -100%; } /* 右下矩形区域 */ .area-bottom-right { background-color: pink; top: 50%; } /* 悬停时背景模糊+透明度变化 */ .area:hover { backdrop-filter: blur(8px); opacity: 0.8; } .content { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -50%); text-align: center; color: #fff; opacity: 0; transition: opacity 0.5s; z-index: 10; } .content-top-left { top: 25%; left: 25%; } .content-bottom-left { top: 75%; left: 25%; } .content-top-right { top: 25%; left: 75%; } .content-bottom-right { top: 75%; left: 75%; } /* 区域hover时显示对应文本 */ .area-top-left:hover ~ .content-top-left, .area-bottom-left:hover ~ .content-bottom-left, .area-top-right:hover ~ .content-top-right, .area-bottom-right:hover ~ .content-bottom-right { opacity: 1; }
修复说明
- 替换伪元素为实际DOM节点:用
.area类的div代替::before伪元素,确保每个视觉区域都能被正确识别hover事件。 - 纯CSS控制交互:利用CSS兄弟选择器
~实现区域hover时对应文本的显示,无需JS,逻辑更可靠。 - 匹配视觉hover范围:调整倾斜区域的尺寸(
height:200%)和位置,让hover触发范围和视觉上的倾斜区域完全一致。 - 添加背景模糊:通过
backdrop-filter: blur(8px)实现悬停时的背景模糊效果,同时调整透明度增强层次感。
内容的提问来源于stack exchange,提问作者Amir
相关产品推荐
相关产品推荐

