温馨提示×

h5左右滑动切换页面如何弄

h5
小亿
392
2024-01-29 15:53:38
栏目: 编程语言

要实现H5左右滑动切换页面,可以通过以下几种方式来实现:

  1. 使用CSS3的transform属性和transition属性,通过监听触摸事件或滚轮事件,在触摸或滚动时改变页面的偏移量。代码示例:

    <style>
      .container {
        width: 100%;
        height: 100vh;
        display: flex;
        overflow: hidden;
        transition: transform 0.3s ease-in-out;
      }
    
      .page {
        width: 100vw;
        height: 100vh;
        flex-shrink: 0;
      }
    </style>
    
    <div class="container">
      <div class="page">Page 1</div>
      <div class="page">Page 2</div>
      <div class="page">Page 3</div>
    </div>
    
    <script>
      var container = document.querySelector('.container');
      var pages = document.querySelectorAll('.page');
      var currentPage = 0;
    
      function goToPage(pageIndex) {
        container.style.transform = `translateX(-${pageIndex * 100}vw)`;
        currentPage = pageIndex;
      }
    
      function handleTouchStart(event) {
        startX = event.touches[0].clientX;
      }
    
      function handleTouchEnd(event) {
        var endX = event.changedTouches[0].clientX;
        var deltaX = endX - startX;
    
        if (deltaX > 50 && currentPage > 0) {
          goToPage(currentPage - 1);
        } else if (deltaX < -50 && currentPage < pages.length - 1) {
          goToPage(currentPage + 1);
        }
      }
    
      container.addEventListener('touchstart', handleTouchStart);
      container.addEventListener('touchend', handleTouchEnd);
    </script>
    
  2. 使用JavaScript库,例如Swiper.js、iScroll.js等,它们提供了丰富的配置选项和API,可以更加方便地实现左右滑动切换页面的效果。

    以下是使用Swiper.js库实现左右滑动切换页面的示例代码:

    <link rel="stylesheet" href="https://unpkg.com/swiper/swiper-bundle.min.css" />
    <div class="swiper-container">
      <div class="swiper-wrapper">
        <div class="swiper-slide">Slide 1</div>
        <div class="swiper-slide">Slide 2</div>
        <div class="swiper-slide">Slide 3</div>
      </div>
    </div>
    
    <script src="https://unpkg.com/swiper/swiper-bundle.min.js"></script>
    <script>
      var swiper = new Swiper('.swiper-container', {
        direction: 'horizontal',
        slidesPerView: 'auto',
        mousewheel: true,
        keyboard: true,
      });
    </script>
    

以上是两种常见的实现方式,你可以根据自己的需求选择适合的方式来实现左右滑动切换页面的效果。

0