全局加上 var animate = false; 后动画失效,

来源:6-1 动画函数

淡水狗

2018-04-15 15:45

https://img1.mukewang.com/5ad302ac0001dd7f04080425.jpg



po上代码

<script>
window.onload = function(){
var content = document.getElementById('content'),
    list = document.getElementById('list'),
    buttons = document.getElementById('buttons'),
    icon = buttons.getElementsByTagName('li'),
    prev = document.getElementById('prev'),
    next = document.getElementById('next'),
    index = 1, //默认点亮第一个icon
    animate = false;//动画运行初始关闭
    function showIcon(){
        for(var i = 0; i < icon.length; i++){
            if(icon[i].className == 'on'){
                icon[i].className = '';
              
            }       
        }
        icon[index - 1].className = 'on';
    }

    function animate(offste){
         animate = true;
        var newLeft = parseInt(list.style.left) + offste;
        var time = 300;//移动总时间
        var inteval = 10;//移动间隔时间
        var speed = offste/(time/inteval);//每次位移量
       
        function go(){
            //如果在移动的时候
           if((speed < 0 && parseInt(list.style.left) > newLeft) || (speed > 0 && parseInt(list.style.left) < newLeft)){
              list.style.left = parseInt(list.style.left) + speed + 'px';
              setTimeout(go, inteval)//递归
           }else{ 
                animate = false;
                list.style.left = newLeft + 'px';
                if(newLeft > -500){
                    list.style.left = -2500 + 'px';
                }if(newLeft < -2500){
                    list.style.left = -500 + 'px';
                }
           } 
        }
      go(); 
    }
    next.onclick = function(){
        if(index == 5){
            index = 1;
        }else{
            index +=1;
        }
        showIcon();
        if(!animate){
          animate(-500);
        }
        
    };
    prev.onclick = function(){
        if(index == 1){
            index = 5;
        }else{
          index -= 1;  
        }                   
        showIcon();
        if(!animate){
          animate(500); 
        }
        
    }
    //按钮切换
    for(var i = 0; i < icon.length; i++){ 
                         
        icon[i].onclick = function(){
            if(this.className == 'on'){ //当点击的按钮为当前状态时,跳出函数。不重复执行
                return;
            }
            var myIndex = parseInt(this.getAttribute('index')); //获取Icon的index属性值
            var offset = -500 * (myIndex - index); //偏移量=(当前点击的按钮对应图片的偏移量-初始偏移量)* -500;
            if(!animate){
              animate(offset);  
            }
            
            index = myIndex; //点击后index索引值归为当前状态
            showIcon();
        }
    }
}
</script>


写回答 关注

1回答

  • 淡水狗
    2018-04-15 15:48:34

    已解决。。。

焦点图轮播特效

通过本教程学习您将能掌握非常实用的焦点图轮播特效的制作过程

65324 学习 · 615 问题

查看课程

相似问题