利用 transition 简单实现轮播图

轮播图现在应用很广泛。一般的项目大家都用 swiper 这个插件来实现,swiper插件非常强大,它提供了很多应用场景,大家有兴趣可以去看看。
如果在实际中写个小demo,可能不会去引用复杂的插件,比如写一个小的活动页,直接用原生的来实现就可以了,请看下面代码:

<html>
   <head>
       <title>轮播图</title>
       <style>
            body {
              margin: 0;
              padding: 0;
            }

            .swiper-box {
              position: relative;
              width: 640px;
              margin: 0 auto;
              height: 480px;
              overflow: hidden;
            }


            .swiper-box img {
              position: absolute;
              transition-property: left;
              transition-duration: 1s;
              transition-timing-function: linear;
              left: 640px;
            }

            .swiper-box img.active {
              left: 0;
            }

       </style> 
    
    </head> 
    <body>
      <div class="swiper-box">
         <img class="img1 active" src="http://lorempixel.com/output/nature-q-c-640-480-5.jpg" />
         <img class="img2" src="http://lorempixel.com/output/city-q-c-640-480-10.jpg" />
         <img class="img3" src="http://lorempixel.com/output/food-q-c-640-480-4.jpg" />
      </div>
 

    </body>
    <script>
         var imgs = document.querySelectorAll('img');
         loop(0);

         // 轮播函数
         function loop(index, pre) {
           var timer = null;
           if (pre != null) {
              
             }
           if (timer) {
              clearTimeout(timer);
           }

           timer = setTimeout(()=> {
              // 记录离开显示区图片的index
              var _index  = index;
              // 让当前显示的图片离开显示区
              imgs[index].style.left = '-640px';
              // 判断是否是最后一张图片, 如果是最后一张,则后面一张是第一张
              index = index === imgs.length - 1 ? -1 : index;
              // 这里让后面一张图片进入显示去
              imgs[index + 1].style.left = '0';
              index++;
             
             // 等待当前轮播结束
              setTimeout(()=> {
                // 将离开显示区的图片位置重新放置在右侧等待下一轮进入
                imgs[_index].style.transitionDuration = '0s'; 
                imgs[_index].style.left = '640px';
                imgs[pre].style.transitionDuration = '1s';
                
              }, 1000);

              // 轮播
              loop(index, _index);

           }, 3000)
         }

    </script>

</html>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

丢丢的大神

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值