改进点
加入缓动函数,节流阀
在之前的写法中使用的是过渡效果,会存在当从最后一张图切换至第一张时,会倒退回去,显示出所有的图片;当快速点击切换箭头时会出现动画播放过快,体验感不好,因此查阅资料做出以下改进。
改进的代码:
// 缓动动画函数
function animate (obj,target,callbackFn) {
clearInterval(obj.timer);
obj.timer = setInterval(function () {
let step = (target - obj.offsetLeft) / 10;
step = step >0 ? Math.ceil(step) : Math.floor(step); //正数时向上取整,负数时向下取整
if (obj.offsetLeft == target){
clearInterval(obj.timer);
callbackFn && callbackFn(); // 当有回调函数执行
}
obj.style.left = obj.offsetLeft + step +"px";
},15);
}
// 右箭头点击
let location_i = 0 ; // 点击次数
let circle = 0 ; // 小圆点下标,跟随点击变化
// 节流阀
let flag = true ;
arrow_r.onclick = function () {
if (flag){
flag = false; // 进入函数体关闭节流阀
if (location_i === ul.children.length - 1) {
location_i = 0 ;
ul.style.left = "0px" ;
}
for (let i = 0;i<ol.children.length;i++){
ol.children[i].className ="";//排他思想,清除所有样式
}
circle ++;
if (circle == ol.children.length){
circle = 0;
}
ol.children[circle].className = "change"; // 保留当前节点样式
location_i++;
animate(ul,- location_i*ImgWidth,function () {
flag = true ; // 动画效果执行完毕后,打开节流阀
});
}
};
// // 左箭头点击
arrow_l.addEventListener("click",function () {
if (flag){
flag = false ;// 进入函数体关闭节流阀
if (location_i === 0) {
location_i = ul.children.length - 1 ;
ul.style.left = -location_i * ImgWidth +"px" ;
}
for (let i = 0;i<ol.children.length;i++){
ol.children[i].className =""; // 排他思想清除,所有样式
}
if (circle == 0){
circle = ol.children.length;
}
circle--;
ol.children[circle].className = "change"; // 保留当前节点样式
location_i--;
animate(ul,- location_i*ImgWidth,function () {
flag = true;// 动画效果执行完毕后,打开节流阀
});
}
});