问答详情
源自:5-1 按钮切换

跟着敲不一样。。。

谁有完整的代码,跟着敲为什么会有那么大的差异?

提问者:春风暖阳 2018-11-11 15:36

个回答

  • ceCGR8
    2018-11-23 16:17:09


    window.onload=function(){

    var container=document.getElementById('container');

    var list=document.getElementById('list');

    var buttons=document.getElementById('button').getElementsByTagName('span');

    var prev=document.getElementById('prev');

    var next=document.getElementById('next');

    var index=1; 

    var animated=false;



        //按钮高亮



        function showButton(){

        for (var i = 0; i < buttons.length; i++) {

        buttons[i].className='';

        }

        buttons[index-1].className='on';

        }

        //驱动left的变化,切换图片

        function animate(offset){

        animated=true;

        var newLeft=parseInt(list.style.left)+offset;

            var time=200;//位移总时间

            var interval=10;//位移间隔时间

            var speed =offset/(time/interval);//每次位移量


            //位移之前的判断函数,是否位移

            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,interval);

            }else{

            animated=false;

            list.style.left=newLeft+'px';

            if (newLeft>-600) {

            list.style.left=-3000+'px';

            }

            if(newLeft<-3000){

            list.style.left=-600+'px';

            }

            }

            } 

            go();

        } 

            //右按钮单击

            next.onclick=function(){

            if (index==5) {

            index=1;

            }else{

            index+=1;

            }     

            showButton();

            if (!animated) {

              animate(-600);

            }

            }

            //左按钮单击

            prev.onclick=function(){

            if (index==1) {

            index=5

            }else{

            index-=1;

            }

            showButton();

            if (!animated) {

            animate(+600);

            }     

            }

            for (var i = 0; i < buttons.length; i++) {

            buttons[i].onclick=function(){

            if(this.className=='on'){

            return;

            }

            var myIndex=parseInt(this.getAttribute('index'));

            var offset=-600*(myIndex-index);

            index = myIndex;

            showButton();

            if (!animated) {

            animate(offset);

            }


            }

            }




        }