实现轮播图

实现轮播图

思路:

通过js来控制轮播的图片的样式,可以控制display:none or block 可以控制opacity:‘0’ or ‘1’ 也可以通过z-index来控制图片的摆放顺序。


Html代码:

这里的图片一般是通过绝对定位放在一个div盒子里面,图片堆叠在一起。

[if !supportLists]1. [endif]首先固定外层框的宽度与长度width与height并且设置相对定位

        

            

            

            

        

    

[if !supportLists]2. [endif]将图片显示在一个框中,不让图片排列出来(设置图片:display:absolute)

[if !supportLists]3. [endif]设置左右移动的按钮


            

            

        

[if !supportLists]4. [endif]设置下面显示的点(显示)


            

            

            

        


[if !supportLists]5. [endif]页面设置完了之后,需要设置行为(js)

var imgs=document.getElementsByClassName("carousel_img");

            var spans=document.getElementsByClassName("carousel_span");

            function InitMove(index){

                for(var i=0;i

                    imgs[i].style.opacity='0';

                    spans[i].style.background='#ccc';

                }

                imgs[index].style.opacity='1';

                spans[index].style.background='red';

            }

主要功能是将index的东西,将其设置透明度为1,下面的span背景设置成red

//第一次初始化,将第一个图片显示出来

            InitMove(0);

//设置当图片到最后一张的时候,自动返回到第一个,否则++将count传递过去

var count=1;

            function fMove(){

                if(count==imgs.length){

                    count=0;

                }

                InitMove(count);

                count++;

            }






//设置自动轮播定时器;

            var scollMove=setInterval(fMove,2500);

//点击下一张和上一张的事件

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

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

            btnleft.onclick=function(){

                clearInterval(scollMove);

                if(count==0){

                    count=imgs.length;

                }

                count--;

                InitMove(count);

                scollMove=setInterval(fMove,2500);

            };


btnright.onclick=function(){

                clearInterval(scollMove);

                fMove();

                scollMove=setInterval(fMove,2500);

            };

//鼠标浮动在上方的时候,停止定时器,当鼠标移出来时,重新开始定时器

var  scollimg = document.getElementById("scollimg");

scollimg.onmouseover=function(){

console.log('hover');

clearInterval(scollMove);

};

scollimg.onmouseout=function(){

console.log('hoverout');

scollMove=setInterval(fMove,2500);

};

你可能感兴趣的:(实现轮播图)