
本文介绍如何使用 CSS radial-gradient 配合 CSS 自定义属性与伪元素,创建一个以鼠标为中心、可动态移动的圆形聚光灯效果,真正“照亮”黑色背景中的内容,而非简单叠加图层。
本文介绍如何使用 css `radial-gradient` 配合 css 自定义属性与伪元素,创建一个以鼠标为中心、可动态移动的圆形聚光灯效果,真正“照亮”黑色背景中的内容,而非简单叠加图层。
要实现真正具有“揭示内容”能力的聚光灯效果(即:仅在光圈范围内显示内容,其余区域保持纯黑),关键在于不添加遮罩层,而是用带透明中心的径向渐变作为背景遮罩,并通过 background-position 动态定位光心——这比用绝对定位的
✅ 核心思路解析
-
避免 DOM 干扰:不插入额外 或
作为光斑,改用 .box::before 伪元素承载遮罩背景;
- 遮罩原理:使用 radial-gradient(circle, transparent 0%, rgba(0,0,0,0.4) Xpx, black Ypx) 构建「中心透明 → 外围渐暗 → 完全遮蔽」的环形掩膜;
- 动态定位:通过 JavaScript 实时更新 --flashlight-x-pos 和 --flashlight-y-pos,驱动 background-position 跟随鼠标移动;
- 性能优化:getBoundingClientRect() 提前计算一次(避免在 mousemove 中反复调用),显著降低重排开销;
- 光标融合:将自定义光标也转为伪元素(.box::after),通过 transform: translate() 精确居中于光心,视觉上形成“光标即光源”的统一感。
?️ 完整实现代码
HTML(精简结构)
<div id="app"> <div class="box"> <h1>Light</h1> </div> </div>CSS(关键遮罩与定位)
.box { display: flex; align-items: center; justify-content: center; cursor: none; width: 100%; padding: 5rem; background-color: #000; overflow: hidden; position: relative; /* 初始光心偏移至可视区外,实现“隐藏”效果 */ --flashlight-x-pos: -200px; --flashlight-y-pos: -200px; --flashlight-inset: -300px; /* 控制 ::before 的 inset 范围 */ } /* 聚光灯遮罩层(伪元素)*/ .box::before { content: ''; position: absolute; inset: var(--flashlight-inset); /* 覆盖整个容器及扩展区域 */ background-image: radial-gradient( circle, transparent 0%, rgba(0, 0, 0, 0.3) 80px, black 100% ); background-position: var(--flashlight-x-pos) var(--flashlight-y-pos); background-repeat: no-repeat; z-index: 1; } /* 自定义光标(伪元素,替代 img 标签)*/ .box::after { content: ''; position: absolute; width: 50px; height: 50px; background: url('https://picsum.photos/50') no-repeat center / contain; border-radius: 50%; pointer-events: none; z-index: 2; transform: translate( calc(var(--flashlight-x-pos) - 25px), calc(var(--flashlight-y-pos) - 25px) ); }JavaScript(轻量响应式控制)
const box = document.querySelector('.box'); const rect = box.getBoundingClientRect(); // ✅ 提前获取,避免高频计算 box.addEventListener('mousemove', (e) => { const x = e.clientX - rect.left; const y = e.clientY - rect.top; // 光心坐标相对于 .box 中心点(实现“居中跟随”) box.style.setProperty('--flashlight-x-pos', `${x - rect.width / 2}px`); box.style.setProperty('--flashlight-y-pos', `${y - rect.height / 2}px`); }); box.addEventListener('mouseleave', () => { // 鼠标离开时,将光心移出视口,确保完全隐藏 box.style.setProperty('--flashlight-x-pos', '-300px'); box.style.setProperty('--flashlight-y-pos', '-300px'); });⚠️ 注意事项与进阶建议
- 渐变半径适配:radial-gradient 中的像素值(如 80px, 100px)需根据实际设计需求调整;若需更大光圈,同步增大数值并适当增加 inset 值(如 inset: -500px),防止边缘裁切;
- 兼容性保障:inset 是现代 CSS 属性(Chrome 110+/Firefox 119+),旧版浏览器可用 top/right/bottom/left: -300px 替代;
- 性能再优化:对高刷新率设备(如 120Hz),可添加 throttle 或 requestAnimationFrame 包裹 mousemove 回调;
- 无障碍提示:聚光灯效果可能影响屏幕阅读器体验,建议为 .box 添加 aria-live="polite" 并在 JS 中同步更新描述性文本;
- 自定义光标图像:.box::after 中的 background-image 可替换为任意 SVG 或 PNG(推荐使用 mask-image + background 实现更精细的光晕边缘)。
该方案不仅解决了原始问题中“radial-gradient 无法揭示内容”的误区,更以声明式 CSS 为主、极简 JS 为辅,达成高性能、易维护、视觉精准的聚光灯交互体验。










