码迷,mamicode.com
首页 > 其他好文 > 详细

类实现轮播图

时间:2021-03-29 12:53:35      阅读:0      评论:0      收藏:0      [点我收藏+]

标签:sele   radius   focus   query   lis   use   undefined   generator   interval   

  

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        *{margin:0;padding:0;}
        ul,ol,li{list-style:none;}
        .banner{
           width:600px;
           height:400px;
           border:10px solid #333;
           margin:100px auto;
           position:relative; 
           overflow:hidden;
        }
        .banner>ul{
            width:500%;
            height:100%;
            position:absolute;
            left:0;
            top:0;            
            /* overflow:hidden; */
        }
        .banner>ul>li{
            width:600px;
            height:100%;
            float:left;
            font-size:100px;
            line-height:400px;
            text-align:center;
        }
        .banner>ol{
            width:175px;
            height:25px;
            background-color:rgba(0,0,0,0.5);
            position:absolute;
            border-radius:15px;
            left:50%;
            bottom:30px;
            /* margin-left:-93px; */
            transform:translateX(-50%);
            padding-top:5px;
            padding-right:15px;
        }
        .banner>ol>li{
            width:20px;
            height:20px;
            background-color: rgb(157, 238, 6);
            border-radius:50%;
            float:left;
            margin-left:15px;
            cursor:crosshair;
        }
        .banner>ol>li.active{
            background-color:rgb(78, 9, 240);
        }
        .banner>div{
            width:100%;
            height:60px;
            position:absolute;
            left:0;
            top:50%;
            margin-top:-30px;
        }
        .banner>div>p{
            float:left;
            width:40px;
            height:100%;
            background-color: rgba(0,0,0,0.5);
            line-height:60px;
            text-align:center;
            font-size:30px;
            color:#fff;
            cursor:e-resize
        }
        .banner>div>p:last-child{float:right;}
    </style>
</head>
<body>
    <div class="banner">
        <ul class="imgBox">
            <li style="background-color:aqua">1</li>
            <li style="background-color:peru">2</li>
            <li style="background-color:purple">3</li>
            <li style="background-color:seagreen">4</li>
            <li style="background-color:rgb(6, 119, 231)">5</li>
        </ul>
        <ol>
        </ol>
        <div>
            <p class="left"><</p>
            <p class="right">></p>
        </div>
    </div>
    <script src="./utils.js"></script>
    <script>
        class Banner{
            constructor(elem){
                this.elem=document.querySelector(elem)
                this.imgBox=this.elem.querySelector(ul)
                this.pointBox=this.elem.querySelector(ol)
                this.bannerWidth=this.elem.clientWidth
                this.index=1
                this.timer=0
                this.flag=true
                this.init()
            }
            init(){
                this.setPoint()
                this.duplicateElem()
                this.grind()
                this.overOut()
                this.bindEvent()
                this.changeTab()
            }
            setPoint(){
                const num=this.imgBox.children.length
                const frg=document.createDocumentFragment()
                for(let i=0;i<num;++i){
                    const li=document.createElement(li)
                    li.dataset.id=i
                    li.classList.add(focus)
                    if(i===0) li.classList.add(active)
                    frg.appendChild(li)
                }
                this.pointBox.appendChild(frg)
                this.pointBox.style.width=num*35+px
                this.pointBox.style.marginLeft=-this.pointBox.offsetWidth/2
            }
            duplicateElem(){
                const firstElem=this.imgBox.firstElementChild.cloneNode(true)
                const lastElem=this.imgBox.lastElementChild.cloneNode(true)
                this.imgBox.appendChild(firstElem)
                this.imgBox.insertBefore(lastElem,this.imgBox.firstElementChild)
                this.imgBox.style.width=this.imgBox.children.length*100+%
                this.imgBox.style.left=-this.index*this.bannerWidth+px
            }
            grind(){
                this.timer=setInterval(()=>{
                    ++this.index
                    move(this.imgBox,{left:-this.index*this.bannerWidth},this.moveEnd.bind(this))
                },2000)
            }
            moveEnd(){
                if(this.index === this.imgBox.children.length-1) this.index=1
                this.imgBox.style.left=-this.index*this.bannerWidth+px
                if(this.index === 0){
                    this.index=this.imgBox.children.length-2
                    this.imgBox.style.left=-this.index*this.bannerWidth+px
                }
                // for(let i=0;i<this.pointBox.children.length;++i){
                //     this.pointBox.children[i].classList.remove(‘active‘)
                // }
                // this.pointBox.children[this.index-1].classList.add(‘active‘)
                // ;[...this.pointBox.children].forEach(value=>value.classList.remove(‘active‘))
                // this.pointBox.children[this.index-1].classList.add(‘active‘)
                ;Array.prototype.forEach.call(this.pointBox.children,value=>value.classList.remove(active))
                this.pointBox.children[this.index-1].classList.add(active)
                this.flag=true
                console.log(this.pointBox.children)
            }
            overOut(){
                this.elem.addEventListener(mouseover,()=>clearInterval(this.timer))
                this.elem.addEventListener(mouseout,()=>this.grind())
            }
            bindEvent(){
                this.elem.addEventListener(click,e=>{
                    if(e.target.className===left){
                        if(!this.flag) return;
                        this.flag=false
                        this.index--
                        move(this.imgBox,{left:-this.index*this.bannerWidth},this.moveEnd.bind(this))
                    }
                    if(e.target.className===right){
                        if(!this.flag) return;
                        this.flag=false
                        this.index++
                        move(this.imgBox,{left:-this.index*this.bannerWidth},this.moveEnd.bind(this))
                    }
                    if(e.target.className===focus){
                        if(!this.flag) return;
                        this.flag=false
                        this.index=e.target.dataset.id-0+1
                        move(this.imgBox,{left:-this.index*this.bannerWidth},this.moveEnd.bind(this))
                    }
                })
            }
            changeTab(){
                document.addEventListener(visibilitychange,()=>{
                    if(document.visibilityState===hidden){
                        clearInterval(this.timer)
                    }else{
                        this.grind()
                    }
                })
            }
        }

        var b=new Banner(.banner)
        console.log(b)
    </script>
</body>
</html>

 

utils.js

function randomRange(x,y){
    var max=Math.max(x,y);
    var min=Math.min(x,y);
    return Math.floor(Math.random() * (max-min+1)) + min;
}
/**
 * generator a random string represents color
 * @param {BOOLEAN} type true => hexadecimal
 * @return {STRING} random string(rbg,hexadecimal)
 */
function randomColor(type=true){
    if(!type){
        return `rbg(${randomRange(0,255)},${randomRange(0,255)},${randomRange(0,255)})`
    }

    var str=#;
    var _str=‘‘;
    for(var i=0;i<3;++i){
        _str=randomRange(0,255).toString(16).padStart(2,0);
        // _str=randomRange(0,255).toString(16);
        // if(_str.length === 1){
        //     _str=‘0‘+_str;
        // }
        str+=_str;
    }
    return str;
}

/**
 * get time difference
 * @param {Date} t1 time1
 * @param {Date} t2 time2
 * @return {Object} encapsulate timeDiff in Object
 */
function getTimeDiff(t1,t2){
    var diffTime=Math.round(Math.abs(t1.getTime()-t2.getTime())/1000);
    var days=parseInt(diffTime/86400);
    var hours=Math.floor(diffTime%86400/3600);
    var minutes=Math.floor(diffTime%3600/60);
    var seconds=parseInt(diffTime%60);
    return {
        days:days,
        hours:hours,
        minutes:minutes,
        seconds:seconds
    }
}
/**
 * Parse QueryString
 * @param {String} str window.location.search
 * @return {Object} return new Object
 */
function parseQueryString(str){
    var obj={};
    if(str.substr(1)){
        str.slice(1).split(&).forEach(function(value,index){
            var interim=value.split(=);
            obj[interim[0]]=interim[1];
        })
    }
    return obj;
}

// var scrollTop = document.documentElement.scrollTop || document.body.scrollTop;
/**
 * 
 * @param {Element} elem 
 * @param {String} event 
 * @param {Function} handler 
 */
function addEventListener(elem,event,handler){
    if(!elem) throw new Error(element is undefined or null)
    if(elem.nodeType !== 1) throw new Error(elem.nodeType !== 1)
    if(elem.addEventListener){
        elem.addEventListener(event,handler)
    }
}
/**
 * 
 * @param {*} elem 
 * @param {*} obj 
 */
function animation(elem,obj){
    for(let key in obj){
        console.log(key);
        let step=parseInt(getComputedStyle(elem)[key]);
        let increment=(obj[key]-step)/10;
        if(key === opacity){
            let timer=setInterval(function(){
                console.log(step,increment)
                step+=increment;
                elem.style[key]=step;
                if(Math.abs(step-obj[key])<0.001) clearInterval(timer);
            })

        }else{
            let timer=setInterval(function(){
                // step+=50;
                step+=increment;
                elem.style[key]=step+px;
                if(Math.abs(step-obj[key])<2) clearTimeout(timer);
            },30)
        }
    }
}

function move(ele, target, fn = () => {}) {
    let count = 0
    for (let key in target) {
      if (key === opacity) target[key] *= 100
      count++
      let timer = setInterval(() => {
        let current = key === opacity ? getStyle(ele, opacity) * 100 : parseInt(getStyle(ele, key))
        let distance = (target[key] - current) / 10
        distance = distance > 0 ? Math.ceil(distance) : Math.floor(distance)
        if (current === target[key]) {
          clearInterval(timer)
          count--
          if (!count) fn()
        } else {
          ele.style[key] = key === opacity ? (current + distance) / 100 : current + distance + px
        }
      }, 10)
    }
  }
  function getStyle(ele, style) {
    // 判断 window 里面有没有 getComputedStyle()
    if (getComputedStyle in window) {
      // 标准浏览器
      return window.getComputedStyle(ele)[style]
    } else {
      // IE 低版本
      return ele.currentStyle[style]
    }
  }   

 

类实现轮播图

标签:sele   radius   focus   query   lis   use   undefined   generator   interval   

原文地址:https://www.cnblogs.com/dissipate/p/14587878.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!