js手写轮播图

1、先思考 轮播图是怎么实现的?

2、手动搭建模型

3、写JS

首先我们要知道轮播图的图片应为动态添加,这样后期才方便添加别的图片,当然图片的序号也要动态添加,毕竟得与图片数量对应,然后就是要添加页面左右两边的小箭头了(当鼠标移出轮播图后自动隐藏),已及创建定时器让图片能自动轮播,以及最关键,当图片轮播到最后一页后,会自动将第一张图片添加到后面,最终才能实现轮播效果。
 

搭建Html框架

    <div class="total">
      <ul id="banner">
        <li><img src="./img/1.webp" alt="" /></li>
        <li><img src="./img/2.webp" alt="" /></li>
        <li><img src="./img/3.webp" alt="" /></li>
      </ul>
    </div>

写css

* {
  margin: 0;
  padding: 0;
}
/* 视口宽高 */
.total {
  height: 300px;
  width: 600px;
  border: 1px solid black;
  overflow: hidden;
  text-align: center;
  line-height: 300px;
  font-size: 50px;
}
/* 轮播图实际宽高 */
#banner {
  height: 300px;
  width: 3000px;
}

li {
  float: left;
  width: 600px;
  height: 300px;
  list-style: none;
}
li img {
  height: 100%;
  height: 100%;
}

#banner li:nth-child(1) {
  background-color: red;
}
#banner li:nth-child(2) {
  background-color: blue;
}
#banner li:nth-child(3) {
  background-color: pink;
}

 写js实现动画

    var curindex = 0;
    var maxlen =
      document.getElementById("banner").getElementsByTagName("li").length - 1;
    var timer = null;
    timer = setInterval(() => {
      change_auto();
      console.log("111");
    }, 1000);
    function change_auto() {
      if (curindex < maxlen) {
        curindex++;
        get_next();
      } else {
        curindex = 0;
        get_reset();
      }
    }
    var width = 600;
    function get_next() {
      var totalbanner = document.getElementById("banner");
      totalbanner.style.marginLeft = "-" + width * curindex + "px";
      totalbanner.style.transition = 1 + "s";
    }
    function get_reset() {
      var totalbanner = document.getElementById("banner");
      totalbanner.style.marginLeft = 0 + "px";
      totalbanner.style.transition = 0 + "s";
    }