如何让CSS Transition不影响JavaScript鼠标跟随动画?
解决鼠标跟随圆形放大时干扰JS动画的问题
问题分析
添加transition: 2s后,CSS过渡会默认作用于所有属性的变化——包括JS动态修改的transform属性。这就导致鼠标移动时,圆形的位置变化也被加上了过渡效果,直接破坏了JS实现的平滑跟随逻辑。即便只给.big类加过渡,切换类的瞬间transform的变化依然会被过渡影响,出现卡顿。
解决方案
给过渡指定仅作用于需要动画的属性,彻底排除transform,让CSS过渡只负责放大缩小相关的变化:
Body { background-color: black; overflow: hidden; } div { width: 100%; height: 100vh; display: flex; justify-content: center; align-items: center; } p { color: white; font-size: 30px; } .mouseFollowCircle { width: 50px; height: 50px; border: 3px solid white; border-radius: 999px; position: absolute; z-index: 999; top: -25px; left: -25px; box-shadow: 0 0 10px white; pointer-events: none; backdrop-filter: blur(2px); /* 仅对放大缩小相关属性添加过渡,排除transform */ transition: width 2s, height 2s, top 2s, left 2s, border-width 2s; } .mouseFollowCircle.big { width: 70px; height: 70px; border-width: 1px; top: -35px; left: -35px; }
同时可以简化.big类的代码,删掉和基础类重复的属性(比如border-radius、position等),只保留变化的部分,让代码更简洁。
原理说明
通过明确指定transition的属性列表,让CSS过渡仅处理圆形尺寸、定位偏移和边框宽度的变化,JS控制的transform属性变化完全不受过渡影响,这样鼠标跟随动画和放大缩小动画就能各自独立、正常运行了。
内容的提问来源于stack exchange,提问作者Owen Anderson
相关产品推荐
相关产品推荐

