Home Web Front-end JS Tutorial How to implement full-screen sliding on mobile terminals with JS

How to implement full-screen sliding on mobile terminals with JS

May 14, 2018 am 10:25 AM
javascript slide

This article uses example code to share with you the full-screen sliding effect on mobile based on js. The basic idea is to detect the sliding direction of the finger, obtain the position when the finger is lifted, and subtract the position when the finger is pressed. The correct result is the direction. After sliding down, this article will share with you the example code of JS to realize full screen sliding on the mobile terminal.

Basic idea:

1) Detect the finger sliding direction: get the position when the finger is lifted, subtract the position when the finger is pressed , getting it right means sliding down

2) After lifting the finger, change the position of the current page in the corresponding reverse operation

The specific code is as follows:

html

<p id="wrap">
  <p id="page01" class="pages">第一屏</p>
  <p id="page02" class="pages">第二屏</p>
  <p id="page03" class="pages">第三屏</p>
  <p id="page04" class="pages">第四屏</p>
</p>
<p id="dots">
  <span class="now"></span><span class=""></span><span class=""></span><span class=""></span>
</p>
Copy after login

css

*{
      margin:0;
      padding:0;
    }
    body{
      overflow: hidden;
    }
    #wrap > p{
      width: 10rem;
      position: absolute;
      left: 0;
      top: 0;
      background: #fff;
      transition: all 0.3s ease;
    }
    #dots{
      position: fixed;
      right: 5px;
      top: 40%;
      z-index: 9;
    }
    #dots span{
      display: block;
      height: 0.2rem;
      width: 0.2rem;
      border: 1px solid #000;
      border-radius: 50%;
      margin-bottom: 3px;
    }
    #dots .now{
      background: #555;
    }
Copy after login

js is divided into two parts

First, set the font-size of the html tag in order to set the base of rem (put in Page header)

document.getElementsByTagName("html")[0].style.fontSize = window.innerWidth/10 + "px";
Copy after login

Second, the specific sliding operation code

 window.onload = function(){
      var op = document.getElementById("wrap");
      var aPages = op.getElementsByClassName("pages");
      var aDots = document.getElementById("dots").getElementsByTagName("span");
      var winH = window.innerHeight;
      var tTime = 1;
      //设置每页的高度和zindex值
      for(var i=0; i<aPages.length; i++){
        aPages[i].style.height = winH + "px";
        aPages[i].style.zIndex = 1;
      }
      aPages[0].style.zIndex = 3;
      aPages[1].style.zIndex = 2;
      op.style.height = winH + "px";
      //手指拖动事件(去除默认动作)
      document.addEventListener("touchmove",function(e){
        e.preventDefault();
      });
      var YStart = 0;
      var iNow = 0;
      //手指按下
      op.addEventListener("touchstart",function(e){
        YStart = e.changedTouches[0].clientY;
      });
      //手指移动
      op.addEventListener("touchmove",function(e){
        disY = e.changedTouches[0].clientY-YStart; //向下滑正,向上滑负
      });
      //手指离开
      op.addEventListener("touchend",function(e){
        disY = e.changedTouches[0].clientY-YStart; //向下滑正,向上滑负
        if(Math.abs(disY)>winH/20){ //只有当滑动距离大于了一定值得时候,才执行切换
          if(disY<0){
            iNow++;
            if(iNow>=aDots.length){
              iNow = 0;
            }
            aPages[0].style.transform = "translateY("+ -winH +"px)";
            doSlide();
          }else{
            iNow--;
            if(iNow<0){
              iNow = aDots.length-1;
            }
            aPages[0].style.transform = "translateY("+ winH +"px)";
            doSlide("up");
          }
        }
      });
      function doSlide(upflag){
        for(var i=0;i<aDots.length;i++){
          aDots[i].className = "";
        }
        aDots[iNow].className = "now";
        if(upflag){
            //向上滑
            aPages[3].style.zIndex = 2;
            aPages[1].style.zIndex = 1;
            op.insertBefore(aPages[3],aPages[1]);
            setTimeout(function(){
              aPages[1].style.transform = "translateY(0px)";
              aPages[1].style.zIndex = 2;
              aPages[0].style.zIndex = 3;
            },300)
        }else{
          setTimeout(function(){
            aPages[0].style.transform = "translateY(0px)";
            aPages[0].style.zIndex = 1;
            aPages[1].style.zIndex = 3;
            aPages[2].style.zIndex = 2;
            op.appendChild(aPages[0]);
          },300)
        }
      }
    }
Copy after login

Okay, let me share with you a simple code to implement full-page sliding on the mobile side with JS Screen display, the specific code is as follows:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8"/>
    <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=0" />
    <meta name="format-detection" content="telephone=no" />
    <meta content="yes" name="mobile-web-app-capable">
    <meta content="yes" name="apple-mobile-web-app-capable" />
    <meta http-equiv="Cache-Control" content="no-siteapp" />
    <title>移动端整页滑屏示例</title>
    <style type="text/css">
      * {
        padding: 0;
        margin: 0;
        font-family: Verdana;
      }
      body,
      html {
        height: 100%;
        background-color: #000000;
      }
      .wrap {
        width: 100%;
        height: 100%;
        overflow: hidden;
      }
      .wrap2 {
        width: 100%;
        height: 1000%;
        transition: 0.3s linear
      }
      .page {
        width: 100%;
        height: 10%
      }
      .page {
        background-color: #fdfdfd;
        font-size: 100px;
        line-height: 400px;
        text-align: center;
        font-weight: bold;
      }
    </style>
  </head>
  <body>
    <p class="wrap" id="wrap">
      <p class="wrap2" id="wrap2">
        <p class="page">1</p>
        <p class="page" style="background-color:#dddddd;">2</p>
        <p class="page">3</p>
        <p class="page" style="background-color:#dddddd;">4</p>
        <p class="page">5</p>
        <p class="page" style="background-color:#dddddd;">6</p>
      </p>
    </p>
    <script type="text/javascript">
      //重要!禁止移动端滑动的默认事件
      document.body.addEventListener(&#39;touchmove&#39;, function(event) {
        event = event ? event : window.event;
        if(event.preventDefault) {
          event.preventDefault()
        } else {
          event.returnValue = false
        }
      }, false)
      var pages = function(obj) {
        var box = document.getElementById(obj.wrap);
        var box2 = document.getElementById(obj.wrap2);
        var len = obj.len;
        var n = obj.n;
        var startY, moveY, cliH;
        //获取屏幕高度
        var getH = function() {
          cliH = document.body.clientHeight
        };
        getH();
        window.addEventListener(&#39;resize&#39;, getH, false);
        //touchStart
        var touchstart = function(event) {
          if(!event.touches.length) {
            return;
          }
          startY = event.touches[0].pageY;
          moveY = 0;
        };
        //touchMove
        var touchmove = function(event) {
          if(!event.touches.length) {
            return;
          }
          moveY = event.touches[0].pageY - startY;
          box2.style.transform = &#39;translateY(&#39; + (-n * cliH + moveY) + &#39;px)&#39;; //根据手指的位置移动页面
        };
        //touchEnd
        var touchend = function(event) {
          //位移小于+-50的不翻页
          if(moveY < -50) n++;
          if(moveY > 50) n--;
          //最后&最前页控制
          if(n < 0) n = 0;
          if(n > len - 1) n = len - 1;
          //重定位
          box2.style.transform = &#39;translateY(&#39; + (-n * 10) + &#39;%)&#39;; //根据百分比位置移动页面
          console.log(n)
        };
        //touch事件绑定
        box.addEventListener("touchstart", function(event) {
          touchstart(event)
        }, false);
        box.addEventListener("touchmove", function(event) {
          touchmove(event)
        }, false);
        box.addEventListener("touchend", function(event) {
          touchend(event)
        }, false);
      };
      pages({
        wrap: &#39;wrap&#39;, //.wrap的id
        wrap2: &#39;wrap2&#39;, //.wrap2的id
        len: 6, //一共有几页
        n: 0 //页面一打开默认在第几页?第一页就是0,第二页就是1
      });
    </script>
  </body>
</html>
Copy after login

Related recommendations:

Example of how to implement left and right sliding using CSS on the mobile terminal

WeChat applet implements the effect of sliding to the left to delete

News sliding special effects implementation code at the bottom of JS (imitation of Vanke)

The above is the detailed content of How to implement full-screen sliding on mobile terminals with JS. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

What should I do if my mobile phone screen is hard to slide and dry? What should I do if my mobile phone screen is hard to slide and dry? Dec 04, 2023 pm 03:51 PM

Solutions for mobile phone screens that are difficult to slide and dry: 1. Humidify the screen; 2. Clean the screen regularly; 3. Increase the sliding strength of your fingers; 4. Use mobile phone screen protectors; 5. Replace protective covers; 6. Keep hands moist; 7. , handle it cleanly when applying the film; 8. Use lubricant; 9. Use gloves; 10. Adjust the screen brightness; 11. Replace the mobile phone. Detailed introduction: 1. Humidify the screen, place a humidifier next to the screen or spray some water to increase the humidity in the air, thereby reducing the dryness of the screen; 2. Clean the screen regularly, use professional screen cleaner, etc.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

How to use insertBefore in javascript How to use insertBefore in javascript Nov 24, 2023 am 11:56 AM

Usage: In JavaScript, the insertBefore() method is used to insert a new node in the DOM tree. This method requires two parameters: the new node to be inserted and the reference node (that is, the node where the new node will be inserted).

See all articles