轮播图 封装函数

250 阅读1分钟

1.封装动画函数代码默写 X轴上

function animate (obj,target,callback){ removeInterval(obj.timer); obj.timer = setInterval(function(){ var step = (target-obj.offsetLeft)/10;

    step = step>0 ? Math.ceil(step) : Math.floor(step);
    
    if(obj.style.left == target){

        removeInterval(obj.timer);

        callback && callback()
        //这句话等同于 callback可在任意处调用 只要需要 这是个回调函数
        if(callback){
            callback()
        }
    }
    obj.style.left = obj.offsetLeft + step + 'px';
},30)

2.这段封装函数的作用

1.可以 使 obj 由原来的位置移动到 obj.style.left = target位置;

2.target不是指移动多少 而是使obj.style.left = target;

3.var  step = 0; step = step>0 ?Math.ceil(step):Math.floor(step);
这句代码可以使 无论step是正是负 都不会取到1 防止 obj.style.left运行到一定程度时 出现 obj.style.left = obj.style.left + step(此时为0) +'px'
4.callback回调函数

3 轮播动画 由最后一个图转到第一个图的解决方法

1.让最后一个图与第一个图一样
2.在外面设一个 var num = 0; 每次点击轮播 num++ 或--
3.转到最后一个图后并没用停止 还再执行了一个方法(让 num = 0; obj.style.left = 0+'px')因为此方法在 30毫秒内瞬间完成 人眼无法捕获 故此可实现由最后一个图转到第一个图
4.方法 简单代码 
if(num == li.length-1 ){
    animate(obj,target,function(){
        num = 0;
        obj.style.left = 0 + 'px'
    })
}