以下是一个简单的鼠标跟随特效,使用HTML/CSS和JavaScript实现:
HTML:
<div id="follower"> </div>
CSS:
#follower { position: absolute; width: 20px; height: 20px; border-radius: 50%; background-color: red; opacity: 0.5; transition: all 0.3s ease-out; }
JavaScript:
const follower = document.getElementById("follower"); document.addEventListener("mousemove", (event) => { const x = event.clientX; const y = event.clientY; follower.style.left = x + "px"; follower.style.top = y + "px"; });
上述代码创建了一个圆形的跟随者(红色圆点),它始终跟随鼠标移动。我们在文档上添加了一个鼠标移动事件监听器,每当鼠标移动时,在鼠标上设置跟随者的位置坐标。注意,跟随者必须具有“绝对”或“固定”定位,这样才能相对于文档移动。 最后,我们指定了CSS transition属性,以使跟随者的位置变化显得更平滑。