使用js写轮播图

99 阅读1分钟

CSS部分

  • { margin: 0; padding: 0; }

     #main {
         margin: 0 auto;
         width: 600px;
         height: auto;
         position: relative;
     }
    
     ul,
     li {
         list-style: none;
     }
    
     #list {
         display: flex;
         position: absolute;
         bottom: 0;
         right: 20px;
     }
    
     #list li {
         width: 30px;
         height: 30px;
         line-height: 30px;
         background-color: #FCBECD;
         color: #fff;
         list-style: none;
         text-align: center;
         margin-left: 10px;
         z-index: 99;
     }
    
    
     #outbox {
         width: 600px;
         height: 373px;
         overflow: hidden;
         position: relative;
    
     }
    
     #allbox {
         position: absolute;
         left: 0px;
         width: 3000px;
         transition: all 1000ms;
     }
    
     .box {
         width: 600px;
         height: 400px;
         float: left;
     }
    
     img {
         width: 600px;
     }
     
    

image.png

JS部分 // 获取标签 var list = document.getElementById('list') var oli = document.getElementById('list').children var boxw = document.querySelector('#allbox') var a = 0 // 设置定时器 var timer1 = setInterval(aa, 1000)

    // 鼠标移入标签是可以索引到指定的图片,关闭定时器
    list.onmouseover = function (e) {
        var e = e || event
        var target = e.target;//获取鼠标选中时li的下标
        clearInterval(timer1);//关闭定时器
        for (var j = 0; j < oli.length; j++) {//排他
            oli[j].style.background = '#FCBECD'
        }
        for (i = 0; i < oli.length; i++) {
            if (target == oli[i]) {
                oli[i].style.background = '#96CCE8'//改变背景颜色
                boxw.style.left = -600 * i + 'px'//索引图片
                return a = i;  
            }
        }
    }
    //鼠标移出时开启定时器
        list.onmouseout = function () {
            timer1 = setInterval(aa, 1000)
        }

    function aa() {
        if (a == 4) a = 0//清空a
        for (var i = 0; i < oli.length; i++) {
            oli[i].style.background = '#FCBECD'
        }
        oli[a].style.background = '#96CCE8'
        boxw.style.left = -600 * a + 'px'
        a++
    }