原生js实现移动端页面平滑切换

<!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>
  </head>
  <style>
    * {
      padding: 0;
      margin: 0;
    }
    html,
    body {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    #app {
      width: 100%;
      height: 100%;
      overflow: hidden;
    }
    .page {
      width: 400%;
      height: 100%;
      display: flex;
      transition: all 1000ms;
    }
    .page_item {
      width: 100%;
      height: 100%;
      flex: 1;
      flex-wrap: nowrap;
    }
    .page_item:nth-child(1) {
      background: red;
    }
    .page_item:nth-child(2) {
      background: orange;
    }
    .page_item:nth-child(3) {
      background: blue;
    }
    .page_item:nth-child(4) {
      background: yellow;
    }
  </style>
  <body>
    <div id="app">
      <div class="page">
        <div class="page_item">PAGE1</div>
        <div class="page_item">PAGE2</div>
        <div class="page_item">PAGE3</div>
        <div class="page_item">PAGE4</div>
      </div>
    </div>
  </body>
  <script>
    const oPage = document.getElementsByClassName("page");
    const oApp = document.getElementById("app");
    const apptWidth = oApp.offsetWidth;
    console.log(apptWidth);
    let startX = 0;
    let moveX = 0;
    let index = 0;
    oApp.addEventListener("touchstart", touchstart, false);
    oApp.addEventListener("touchmove", touchmove, false);
    oApp.addEventListener("touchend", touchend, false);

    function touchstart(e) {
      startX = e.touches[0].clientX;
    }

    function touchmove(e) {
      moveX = e.touches[0].clientX - startX;
      translateX(-index * apptWidth + moveX);
    }

    function touchend() {
      if ((index == 0 && moveX > 0) || (index == 3 && moveX < 0)) {
        translateX(-index * apptWidth);
        return;
      }
      if (Math.abs(moveX) > apptWidth / 3) {
        if (moveX > 0) {
          index = index - 1;
        } else {
          index = index + 1;
        }
      }
      translateX(-index * apptWidth);
      startX = 0;
      moveX = 0;
    }

    function translateX(X) {
      oPage[0].style.transform = `translateX(${X}px)`;
      //   oPage[0].style.transform = "translateX(100px)";
    }
  </script>
</html>
posted @ 2022-01-04 17:06  coderlq  阅读(333)  评论(0)    收藏  举报