如何为基于translate属性的自定义移动鼠标添加运动模糊效果
给自定义鼠标添加运动模糊效果
下面提供两种实用的实现方案,让你的自定义鼠标移动时更流畅自然:
方案1:CSS滤镜+过渡实现基础运动模糊
通过在鼠标移动时动态添加模糊滤镜,配合伪元素拖影,快速实现基础效果。
HTML(无需修改)
<div class="mover"> <svg width="24" height="24" viewBox="0 0 24 24"> <path d="M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z"></path> </svg> </div>
CSS 修改
.mover { width: 50px; height: 50px; position: fixed; left: -8px; top: -6px; transition-duration: .1s; transition-timing-function: ease-out; filter: blur(0px); } /* 伪元素创建半透明拖影 */ .mover::after { content: ''; position: absolute; width: 100%; height: 100%; left: 0; top: 0; background: url('data:image/svg+xml;utf8,<svg width="24" height="24" viewBox="0 0 24 24"><path d="M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z"></path></svg>') center no-repeat; opacity: 0.5; filter: blur(2px); transition-duration: .15s; transition-timing-function: ease-out; } html { cursor: none; } body { background: #F5F9FF; height: 3000px; }
JS 修改
const mover = document.querySelector('.mover'); document.addEventListener("mousemove", e => { // 移动时添加模糊 mover.style.filter = 'blur(1px)'; mover.style.transform = `translate(${e.pageX}px, ${e.pageY}px)`; // 停止移动后清除模糊 clearTimeout(mover.blurTimer); mover.blurTimer = setTimeout(() => { mover.style.filter = 'blur(0px)'; }, 100); });
方案2:多元素拖影实现真实运动模糊
通过创建多个分层的拖影元素,利用延迟跟随和不同的透明度/模糊值,模拟更自然的运动轨迹。
HTML 修改
<div class="mover-container"> <div class="mover"></div> <div class="mover"></div> <div class="mover"></div> </div>
CSS
.mover-container { position: fixed; left: -8px; top: -6px; pointer-events: none; /* 避免干扰鼠标事件 */ } .mover { width: 50px; height: 50px; position: absolute; background: url('data:image/svg+xml;utf8,<svg width="24" height="24" viewBox="0 0 24 24"><path d="M12,11.5A2.5,2.5 0 0,1 9.5,9A2.5,2.5 0 0,1 12,6.5A2.5,2.5 0 0,1 14.5,9A2.5,2.5 0 0,1 12,11.5M12,2A7,7 0 0,0 5,9C5,14.25 12,22 12,22C12,22 19,14.25 19,9A7,7 0 0,0 12,2Z"></path></svg>') center no-repeat; transition-duration: .12s; transition-timing-function: ease-out; } /* 分层设置拖影的透明度和模糊 */ .mover-container .mover:nth-child(2) { opacity: 0.6; filter: blur(1.5px); transition-duration: .09s; } .mover-container .mover:nth-child(3) { opacity: 0.3; filter: blur(3px); transition-duration: .06s; } html { cursor: none; } body { background: #F5F9FF; height: 3000px; }
JS
const movers = document.querySelectorAll('.mover'); document.addEventListener("mousemove", e => { // 给每个拖影设置延迟跟随,形成轨迹 movers.forEach((mover, index) => { setTimeout(() => { mover.style.transform = `translate(${e.pageX}px, ${e.pageY}px)`; }, index * 20); }); });
内容的提问来源于stack exchange,提问作者Joel Smith
相关产品推荐
相关产品推荐

