详解轮播图循环切换闪动及解决方案
很多轮播图组件在循环切换到首图时,尤其当用户点击切换按钮较慢或多次点击时,会出现明显的闪动。这通常与使用 translate3d 动画变换有关。本文将分析其原因并提供解决方案。
问题根源在于:使用 translate3d 动画时,浏览器需要复杂的计算和渲染。从最后一页切换到第一页时,若动画未完成,用户又触发了新的切换,动画就会中断,导致闪动。
改进后的 changeCur 方法有效解决了这个问题。其核心思路是:在循环切换时,先将 transitionDuration 设置为 0s,让动画瞬间完成;然后通过 this.con.offsetWidth 强制浏览器重新计算容器布局;最后再将 transitionDuration 恢复为 .3s,确保动画平滑过渡。
改进后的代码如下:
changeCur(add) { this.con.style.transitionDuration = '.3s'; let cur = parseInt(this.out.style.getPropertyValue('--cur')); if (add) { if (cur === this.num) { this.con.style.transitionDuration = '0s'; this.setCur(0); this.con.offsetWidth; // 强制刷新布局 this.con.style.transitionDuration = '.3s'; this.setCur(1); } else { this.setCur(cur + 1); } } else { if (cur === 1) { this.con.style.transitionDuration = '0s'; this.setCur(this.num + 1); this.con.offsetWidth; // 强制刷新布局 this.con.style.transitionDuration = '.3s'; this.setCur(this.num); } else { this.setCur(cur - 1); } }}
登录后复制
本文来自互联网或AI生成,不代表软件指南立场。本站不负任何法律责任。