用js实现简单轮播图

我们在浏览网页的时候,大部分都会看见中间有几张图片在自己走动,今天就教一下大家怎么实现
首先我们要在html中排个版,在body里边

接下来我们在scss里边给设置一下样式

.box {
    width:800px;
    height:380px ;
    position: relative;
    margin: 0 auto;

    ul {
       width:800px;
       height:380px ;
        overflow: hidden;

        li {
           width:800px;
           height:380px ;
            img {
                width:800px;
               height:380px ;
            }
        }
    }


    button {
      width:60px;
      height:80px
        position: absolute;
        top: 50%;
        margin-top: -40px;
        background-color: rgba(0, 0, 0, 0.4);
        color: #fff;
        font-size: 40px;
        border: none;
        
    }

    #right{
        position: absolute;
        right: 0px;
    }
    ol{
        position: absolute;
        bottom:50px;
        left:135px;
        li{
          width: 20px;
          height: 20px;
          background-color: #fff;
          border-radius: 50%;
          margin:0px 30px;
          float: left;
        }
         .active{
           background-color: pink;
         }
      }
}

接下来就是js部分

var list = document.querySelectorAll('ul li')  //获取图片列表
var rgt = document.getElementById("right")  //右侧点击
var left = document.getElementById("left")   //左侧点击
var box = document.getElementsByClassName("box")[0]  //大盒子
var ol_list = document.querySelectorAll('ol>li');   //下面的原点
var timer = null,  定义一个计时器
    ind = 0;  //定义一个下标

// 封装排他  (只显示自己)
function getpaita() {
    for (var i = 0; i < list.length; i++) {
        list[i].style = "display:none";  //所有图片不显示
        ol_list[i].style = '';  //所有原点不显示
    }
    list[ind].style = "display:block"  //当前图片
    ol_list[ind].style = "background:pink";  //当前原点
}
// 开始轮播
function tim() {
    ind++; //下标增加
    if (ind > list.length - 1) {  //判断 如果下标到了最后临界点则返回第一张
        ind = 0;
    }
    
    getpaita()  //排他
}
timer = setInterval(tim, 1000);
// 划过停止轮播  清除定时器
box.onmouseover = function () {
    clearInterval(timer);
}
// 划出继续执行定时器
box.onmouseout = function () {
    timer = setInterval(tim, 1000);
}

// 右击换下一张
rgt.onclick = function () {
    ind++;
    if (ind > list.length - 1) {
        ind = 0;
    }
    getpaita()
}
// 左击换上一张
left.onclick = function () {
    ind--;
    console.log(ind)
    if (ind < 0) {
        ind = list.length - 1; //如果下标到了前面临界点则返回最后一张
    }
    getpaita()

}

// 原点  划过显示相对应图片
for (var j = 0; j < ol_list.length; j++) {
    ol_list[j].ind = j;
    ol_list[j].onmouseover = function () {
        ind=this.ind;  跟图片下标同步
        getpaita();
    }
}

这就是一个简单轮播,可以放几张图片试试

你可能感兴趣的:(用js实现简单轮播图)