首页 专题 H5案例 前端导航 UI框架

图片轮番详解

作者:TG 日期: 2016-06-09 字数: 4423 阅读: 3612
图片轮播是网站中的常用功能,用于在有限的网页空间内展示一组产品图片或者照片,同时还有非常吸引人的动画效果。
下面,我将介绍一种实现图片轮番的方法。

首先是div:

<div class="swiper-container"> 

   <div class="swiper-wrapper"> 

      <div class="swiper-slide" style="background:red;">index1</div> 

      <div class="swiper-slide" style="background:yellow;">index2</div> 

      <div class="swiper-slide" style="background:green;">index3</div> 

   </div> 

</div>

我们先定义一个class名为swiper-container的外层,然后是内层swiper-wrapper(这一层也是我们轮番的层),最后是每一页,我在这里命名为swiper-slide。
接着是CSS:

<style> * { margin: 0; padding: 0; } body, html { width: 100%; height: 100%; } .swiper-container { width: 100%; height: 100%; margin: 0 auto; overflow: hidden; z-index: 1; } .swiper-wrapper { display: flex; display: -webkit-flex; flex-wrap: nowrap; -webkit-flex-wrap: nowrap; } .swiper-slide, .swiper-wrapper { height: 100%; -ms-transform-style: preserve-3d; -moz-transform-style: preserve-3d; -webkit-transform-style: preserve-3d; } .swiper-slide { width: 100%; height: 100%; -webkit-flex-shrink: 0; -ms-flex: 0 0 auto; flex-shrink: 0; line-height: 300px; color: #fff; text-align: center; } </style>

样式我们使用flex布局,如果不了解flex布局,可以到我的另一篇文章了解一下:Flex布局

最后就是我们的关键JavaScript:

<script>   

  var slides = document.querySelectorAll(".swiper-slide");   

  var wrapper = document.querySelector(".swiper-wrapper");   

  var wWidth = window.innerWidth;   

  var turn = {   

      slides:document.querySelectorAll(".swiper-slide"),   

      wrapper:document.querySelector(".swiper-wrapper"),   

      moveX: (-wWidth),   

      pageInit: function() {   

      for (var i = 0; i < slides.length; i++) {   

         slides[i].style.width = wWidth + "px";   

      }   

      var first = slides[0].cloneNode(true);   

      var last = slides[slides.length - 1].cloneNode(true);   

      wrapper.appendChild(first);   

      wrapper.insertBefore(last, slides[0]);   

      slides = document.querySelectorAll(".swiper-slide");   

      wrapper.style.webkitTransitionDuration = "0ms";   

      wrapper.style.webkitTransform = "translate3d(" + turn.moveX + "px,0px,0px)";   

      turn.loop();   

   },   

   loop: function() {   

   setInterval(function() {   

      wrapper.style.webkitTransitionDuration = "1s";   

      if (Math.abs(turn.moveX) >= (slides.length - 1) * slides[0].offsetWidth) {   

         turn.moveX = (-wWidth);   

         wrapper.style.webkitTransitionDuration = "0ms";   

         wrapper.style.webkitTransform = "translate3d(-" + wWidth + "px,0px,0px)";   

      } else {   

         turn.moveX -= wWidth;   

         wrapper.style.webkitTransform = "translate3d(" + turn.moveX + "px,0px,0px)";   

     }   

   }, 2000);   

   }   

}    

turn.pageInit();


</script>


以后会继续优化的!

目录