Swiper轮播图

2021-04-01 14:08  1668人阅读  评论 (0)
Tags: swiper
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Swiper 轮播图 dotcoo</title>
  <style>
    .list {
      margin: 100px auto;
      border: 16px solid #ccc;
      height: 40px;
      width: 300px;
    }
    .list .item {
      line-height: 40px;
      width: 100%;
      height: 100%;
    }
  </style>
</head>
<body>
  <div class="list">
    <div class="item" style="background-color:#000000aa">00</div>
    <div class="item" style="background-color:#249249aa">01</div>
    <div class="item" style="background-color:#492492aa">02</div>
    <div class="item" style="background-color:#6db6dbaa">03</div>
    <div class="item" style="background-color:#924924aa">04</div>
    <div class="item" style="background-color:#b6db6daa">05</div>
    <div class="item" style="background-color:#db6db6aa">06</div>
  </div>
  <script>
    /**
     * 轮播图
     * @param {string} selector 轮播图容器选择器
     * @param {number} duration 轮播间隔时长
     * @param {number} current 默认显示第几个元素
     * @param {string} direction 滚动方向 top bottom left right
     * @param {boolean} debug 是否调试
     * @returns {number} 定时器id
     */
    function swiper(selector, duration = 3000, current = 0, direction = 'top', debug = false) {
      const vertical = direction == 'top'  || direction == 'bottom'; // vertical horizontal 是垂直还是水平
      const forward = direction == 'top' || direction == 'left'; // forward backward 是前进还是倒退
      const parent = document.querySelector(selector), width = parent.clientWidth, height = parent.clientHeight;
      parent.style.position = parent.style.position || 'relative';
      parent.style.overflow = debug ? '' : (parent.style.overflow || 'hidden');
      const items = document.querySelectorAll(selector + ' > *'), l = items.length;
      const move = () => {
        for (let i = 0, index = (l + current + i - 1) % l, item = items[index]; i < l; i++, index = (l + current + i - 1) % l, item = items[index]) {
          item.style.position = 'absolute';
          if (i < 3) {
            if (i == 0) {
              item.style.transition = forward ? 'all .4s ease-out' : '';
            } else if (i == 1) {
              item.style.transition = 'all .4s ease-out';
            } else if (i == 2) {
              item.style.transition = forward ? '' : 'all .4s ease-out';
            }
            item.style.top  = vertical ? `${(i - 1) * height}px` : 0;
            item.style.left = vertical ? 0 : `${(i - 1) * width}px`;
          } else {
            item.style.transition = '';
            item.style.left = 0;
            item.style.top = `${(index + 3) * height}px`;
          }
        }
        current = (l + current + (forward ? 1 : -1)) % l;
      };
      move();
      return setInterval(move, duration);
    }
    swiper('.list');
  </script>
</body>
</html>

豫ICP备09035262号-1