原生JS实现轮播图

作者: puxiaotaoc | 来源:发表于2018-09-14 10:27 被阅读15次
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
    
    <head>
      <meta charset="utf-8">
      <title></title>
      <style>
        .banner{
          width: 1002px;
          height: auto;
          overflow: hidden;
        }
        .banner img{
          width: 1002px;
          height: 300px;
          overflow: hidden;
          position: absolute;
          background-repeat: no-repeat;
        }
      </style>
    </head>
    
    <body>
      <div class="banner">
        <ul>
          <a href="#"><img src="photo_01.jpeg"></a>
          <a href="#"><img src="photo_02.jpeg"></a>
          <a href="#"><img src="photo_03.jpeg"></a>
          <a href="#"><img src="photo_04.jpeg"></a>
        </ul>
      </div>
    </body>
    <script type="text/javascript">
      var timer = null,
        index = 0,
        pics = document.getElementsByTagName("img");
    
      function slideImg() {
        var banner = document.getElementsByClassName("banner");
        banner.onmouseover = function() {
          stopAutoPlay();
        }
        banner.onmouseout = function() {
          startAutoPlay();
        }
        banner.onmouseout();
      }
      //开始播放轮播图
      function startAutoPlay() {
        timer = setInterval(function() {
          index++;
          if (index > 3) {
            index = 0;
          }
          changeImg();
        }, 1000);
      }
      //暂停播放
      function stopAutoPlay() {
        if (timer) {
          clearInterval(timer);
        }
      }
      //改变轮播图
      function changeImg() {
        for (var i = 0; i < pics.length; i++) {
          pics[i].style.display = "none";
        }
        pics[index].style.display = "block";
      }
      slideImg();
    </script>
    
    </html>
    

    相关文章

      网友评论

        本文标题:原生JS实现轮播图

        本文链接:https://www.haomeiwen.com/subject/alrngftx.html