左右点击切换tab标签的实现

2023-04-27 19:31:23 浏览数 (3)

演示:

代码实现:

代码语言:javascript复制
<!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>Document</title>
  <style>
    .tab-container {
      display: flex;
      align-items: center;
    }

    .tab-arrow {
      font-size: 20px;
      border: none;
      background-color: transparent;
      cursor: pointer;
    }

    .tab-arrow-left {
      margin-right: 10px;
    }

    .tab-wrapper {
      display: flex;
      overflow-x: auto;
      -webkit-overflow-scrolling: touch;
      /* for smooth scrolling on iOS */
      scroll-behavior: smooth;
      /* for smooth scrolling in modern browsers */
      scroll-snap-type: x mandatory;
      -webkit-scroll-snap-type: mandatory;
      -ms-scroll-snap-type: mandatory;
    }

    .tab {
      flex-shrink: 0;
      width: 120px;
      height: 40px;
      line-height: 40px;
      text-align: center;
      background-color: #ddd;
      margin-right: 10px;
      scroll-snap-align: center;
    }
  </style>
</head>

<body>
  <div class="tab-container">
    <button class="tab-arrow tab-arrow-left">❮</button>
    <div class="tab-wrapper">
      <div class="tab">标签1</div>
      <div class="tab">标签2</div>
      <div class="tab">标签3</div>
      <div class="tab">标签4</div>
      <div class="tab">标签5</div>
      <div class="tab">标签6</div>
    </div>
    <button class="tab-arrow tab-arrow-right">❯</button>
  </div>
</body>
<script>
  const tabWrapper = document.querySelector('.tab-wrapper');
  const arrowLeft = document.querySelector('.tab-arrow-left');
  const arrowRight = document.querySelector('.tab-arrow-right');

  arrowLeft.addEventListener('click', function () {
    tabWrapper.scrollBy({
      left: -200,
      behavior: 'smooth'
    });
  });

  arrowRight.addEventListener('click', function () {
    tabWrapper.scrollBy({
      left: 200,
      behavior: 'smooth'
    });
  });
</script>

</html>

0 人点赞