前端学习笔记JavaScript - 轮播图

  • 先上图

首先创建基本框架

  • html代码
  <img src="IMG/ad1.jpg" alt="图片">
  <p>
    <span class="lt">&lt;</span>
    <span class="gt">&gt;</span>
  </p>
  • css代码
    div {
      width: 670px;
      border: 1px solid blue;
      margin: 100px auto;
      position: relative;
    }

    img {
      vertical-align: bottom;
    }

    span {
      height: 60px;
      font-size: 25px;
      color: white;
      background-color: rgba(0,0,0,0.5);
      width: 40px;
      line-height: 60px;
      text-align: center;
    }

    span:hover {
      cursor: pointer;
    }

    div>p {
      position: absolute;
      width: 100%;
      left: 0;
      /*元素垂直居中*/
      top: 50%;
      transform: translateY(-50%);
      /*左右对齐布局*/
      display: flex;
      justify-content: space-between;
    }

  • javascript代码
<script>
    let pre = document.querySelector(".pre");
    let next = document.querySelector(".next");
    let img = document.querySelector("img");
    let imgList = [
      "IMG/ad1.jpg",
      "IMG/ad2.jpg",
      "IMG/ad3.jpg",
      "IMG/ad4.jpg",
      "IMG/ad5.jpg"
    ]

    let imgIndex = 0;
    pre.onclick = function () {
      console.log("kkkk");
      imgIndex--;
      if (imgIndex < 0){
        imgIndex = imgList.length - 1;
      }

      img.src = imgList[imgIndex];
    }

    next.onclick = function () {
      console.log("kkkk");
      imgIndex++;
      if (imgIndex > imgList.length - 1){
        imgIndex = 0;
      }

      img.src = imgList[imgIndex];
    }

  </script>
posted @ 2020-08-13 17:11  cmg123  阅读(123)  评论(0)    收藏  举报