CSS 聚光灯效果

I recently made an experiment about Proximity Reactions. The idea was to create an interactive effect according to the mouse position relative to elements. Then I made a less JavaScript, more CSS version where the only thing JavaScript does is to pass the mouse position into a couple of CSS custom properties. That’s it. All the heavy lifting happened inside the CSS itself, safely away from the JavaScript thread.

我最近做了一个关于接近反应实验。这个想法是根据鼠标相对于元素的位置创建一个交互效果。然后我做了一个更少JavaScript,更多CSS的版本,JavaScript唯一的作用是将鼠标位置传递到几个CSS自定义属性中。就这样。所有的重担都在CSS内部完成,安全地远离JavaScript线程。

That got me thinking: if we can get the mouse position in CSS so easily, what else can we build with that? I started tinkering, trying out different interaction patterns, and eventually got to this Spotlight Effect that’s easy to create, simple to customize, and looks surprisingly slick, all with just a few lines of CSS.

这让我思考:如果我们可以如此轻松地在CSS中获取鼠标位置,我们还可以用它构建什么?我开始尝试,尝试不同的交互模式,最终得到了这个聚光灯效果,它易于创建,简单自定义,并且看起来出奇的流畅,所有这些只需几行CSS。

Let’s take a look at how it works and how you can make it your own, and hopefully you can pick up a few new CSS tricks along the way. 🙂

让我们看看它是如何工作的,以及你如何可以让它成为你自己的,希望你能在这个过程中学到一些新的CSS技巧。😃

To create a spotlight effect that responds to the mouse position, we need to set up two small things before diving into the CSS.

为了创建一个响应鼠标位置的聚光灯效果,我们需要在深入 CSS 之前设置两个小东西。

  1. We need a dedicated spotlight element in the DOM. This is usually placed near the end of the markup so it can sit on top of everything else when needed.
  2. 我们需要在 DOM 中有一个专用的聚光灯元素。通常将其放置在标记的末尾,以便在需要时可以覆盖在其他所有内容之上。
  3. We need just a few lines of JavaScript to pass the mouse coordinates into CSS custom properties.
  4. 我们只需要几行 JavaScript 将鼠标坐标传递到 CSS 自定义属性中。

<div class="spotlight"></div>Code language: HTML, XML (xml)

<div class="spotlight"></div>代码语言:HTML,XML(xml)

document.body.addEventListener('mousemove', (e) => { document.body.style.setProperty('--clientX', e.clientX + 'px'); document.body.style.setProperty('--clientY', e.clientY + 'px'); });Code language: JavaScript (javascript)

document.body.addEvent...

开通本站会员,查看完整译文。

trang chủ - Wiki
Copyright © 2011-2025 iteam. Current version is 2.144.0. UTC+08:00, 2025-06-09 13:10
浙ICP备14020137号-1 $bản đồ khách truy cập$