面向对象轮播图

CSS部分

 #box{
      width:400px;
      height:200px;
      position:relative;
      overflow:hidden;
      border:1px solid black;
     }

HTML部分(写一个div并添加样式)

js部分

function Banner(element,width,height,timeSpace,timeLong,imgs,btnColor,changeColor,btnHeight,btnWidth,isCircle){
        this.element=element;//父元素
        this.width=width;
        this.height=height;
        this.timeSpace=timeSpace;
        this.timer=null;
        this.img = imgs;//图片的src路径
        this.ord=0;
        this.domImgs = null;//img标签

        this.lis=null;
        this.btnColor=btnColor;
        this.changeColor=changeColor;
        this.btnHeight=btnHeight;
        this.btnWidth=btnWidth;
        this.circle=isCircle;
        this.timeLong=timeLong;

        this.createEle=function(){
            for(let i=0;i{
                let outOrd=this.ord;
                this.ord=this.ord+1;
                if(this.ord>=this.img.length){
                    this.ord=0;
                }
                this.showImg(outOrd,this.ord);
              },this.timeSpace);
        }
        this.showImg=function(outOrd,ord){
            let imgs=this.element.children;
            // imgs[ord].style.left = this.width+"px";
            let left1=0;
            let timeSpace=10;
            let step=Math.abs(this.width)/(this.timeLong/timeSpace);
            let direction=-1;
            let myTimer=setInterval(()=>{
                left1+=direction*step;
                if(left1<=-this.width){
                    left1=-this.width;
                    clearInterval(myTimer);
                }
                imgs[outOrd].style.left=left1+"px";
                imgs[ord].style.left=left1+this.width+"px";
            });

            let lis=this.element.lastChild.children;
            for(let i=0;i{
                this.stop();
            }
            this.element.onmouseout=()=>{
                this.autoPlay();
            }

            let lis=this.element.lastElementChild.children;
            for(let i=0;i{
                    this.goImg(parseInt(lis[i].getAttribute("index")));
                };
            }
        }
        this.goImg=function(transIndex){//2
            //1、改变数据(图片序号)
            let outIndex = this.ord;
            this.ord=transIndex;//2
            //2、边界处理
            if(this.ord>this.img.length-1 || this.ord<0){
                this.ord = 0;
            }
            //3、改变外观
            this.showImg(outIndex,this.ord);
        }
        this.createEle();
        this.addEvent();
    }



    window.onload=function(){
        let s1 = new Banner(
            document.getElementById('box'),
            400,
            200,
            3000,
            2000,
            ["./11.jpg","./12.jpg","./24.jpg","./37.jpg"],
            "transparent",
            "red",
            20,
            40,
            false,
        );
        s1.autoPlay();
    }

 

你可能感兴趣的:(javascript)