JS轮播图写法二(改进:加入缓动函数,节流阀)

改进点

加入缓动函数,节流阀

在之前的写法中使用的是过渡效果,会存在当从最后一张图切换至第一张时,会倒退回去,显示出所有的图片;当快速点击切换箭头时会出现动画播放过快,体验感不好,因此查阅资料做出以下改进。

改进的代码:

 // 缓动动画函数 
    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;// 动画效果执行完毕后,打开节流阀
            });
        }
    });
    
  
  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值