JavaScript mobile webpage special effects and local storage (57th)

1. Special effects of mobile web pages

1. Touch events

1.1 Overview of touch screen events

1. The compatibility of mobile browsers is good. We don’t need to consider the compatibility issues of JS in the past, and we can safely use native JS writing effects, but the mobile terminal also has its own unique features. For example, the touch screen event touch (also called touch event), both Android and IOS.

2. The touch object represents a touch point. The touch point could be a finger or a stylus. Touch screen events respond to the user's finger (or stylus) on the screen or trackpad.

3. Common touch screen events are as follows:

    <style>
        div {
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        // 1. Get the element
        // 2. Finger touch DOM element event
        var div = document.querySelector('div');
        div.addEventListener('touchstart', function() {
            console.log('i touched you');

        });
        // 3. Finger moving event on DOM element
        div.addEventListener('touchmove', function() {
            console.log('I keep touching');

        });
        // 4. Finger leaves the DOM element event
        div.addEventListener('touchend', function() {
            console.log('gently i go');

        });
    </script>
</body>

1.2 Touch event object (TouchEvent)

1. TouchEvent is a type of event that describes the state change of a finger on a touch surface (touch screen, touchpad, etc.). This type of event is used to describe one or more touch points, allowing developers to detect the movement of touch points, the increase and decrease of touch points, etc.

2. The three events of touchstart, touchmove and touchend will each have event objects.

3. Key points of touch event objects Let's look at three common object lists:

When our fingers leave the screen, there will be no lists of touches and targetTouches, but there will be changedTouches

Because we usually register touch events for elements, it is important to remember targetTocuhes

console.log(e.targetTouches[0]);
// targetTouches[0] can get the relevant information of the first finger that is touching the dom element, such as the coordinates of the finger, etc.

1.3 Dragging elements on the mobile side

1. touchstart, touchmove, touchend can realize dragging elements
2. But dragging elements requires the coordinates of the current finger. We can use pageX and pageY in targetTouches[0]
3. The principle of dragging on the mobile terminal: when the finger is moving, calculate the distance the finger moves. Then use the original position of the box + the distance moved by the finger
4. The distance moved by the finger: the position of the finger in the sliding minus the position where the finger just touched

Three steps to drag elements:

(1) Touch element touchstart : Get the initial coordinates of the finger and the original position of the box at the same time
(2) Move the finger touchmove: Calculate the sliding distance of the finger and move the box
(3) Leave finger touchend:

Notice:
Finger movement will also trigger the scrolling of the screen, so here we need to prevent the default screen scrolling e.preventDefault();

    <script>
        // (1) Touch element touchstart: Get the initial coordinates of the finger and the original position of the box at the same time
        // (2) Move the finger touchmove: Calculate the sliding distance of the finger and move the box
        // (3) Leave finger touchend:
        var div = document.querySelector('div');
        var startX = 0; //Get the initial coordinates of the finger
        var startY = 0;
        var x = 0; //Get the original position of the box
        var y = 0;
        div.addEventListener('touchstart', function(e) {
            //  Get the initial coordinates of the finger
            startX = e.targetTouches[0].pageX;
            startY = e.targetTouches[0].pageY;
            x = this.offsetLeft;
            y = this.offsetTop;
        });

        div.addEventListener('touchmove', function(e) {
            //  Calculate the movement distance of the finger: subtract the initial coordinates of the finger from the coordinates after the finger moves
            var moveX = e.targetTouches[0].pageX - startX;
            var moveY = e.targetTouches[0].pageY - startY;
            // Move our box The original position of the box + the distance moved by the finger
            this.style.left = x + moveX + 'px';
            this.style.top = y + moveY + 'px';
            e.preventDefault(); // Default behavior to prevent screen scrolling
        });
    </script>

2. Common special effects on the mobile terminal

2.1 classList

The classList attribute is a new attribute in HTML5 that returns the class name of the element. But ie10 and above versions support it. This property is used to add, remove and toggle CSS classes on the element. There are following methods

1. Add class:

focus.classList.add('current');

2. Remove the class:

focus.classList.remove('current');

3. Switching class:

focus.classList.toggle('current');

Note that in the above method, all class names do not have dots

    <style>
        .bg {
            background-color: black;
        }
    </style>

<body>
    <div class="one two"></div>
    <button> switch light</button>
    <script>
        // classList returns the class name of the element
        var div = document.querySelector('div');
        // console.log(div.classList[1]);
        // 1. Adding a class name is to append the class name after it will not overwrite the previous class name. Note that it does not need to be added before.
        div.classList.add('three');
        // 2. Delete the class name
        div.classList.remove('one');
        // 3. Switch class
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            document.body.classList.toggle('bg');
        })
    </script>
</body>

2.2 click delay solution

There will be a 300ms delay in the click event on the mobile terminal, because double tap to zoom on the mobile terminal screen will zoom the page. solution:
(1) Disable scaling
The browser disables the default double tap zoom behavior and removes the 300ms tap delay.

<meta name="viewport" content="user-scalable=no">

(2) Use the touch event to encapsulate this event yourself to solve the 300ms delay.

The principle is:

1. When our fingers touch the screen, record the current touch time
2. When our finger leaves the screen, subtract the touch time from the time of leaving
3. If the time is less than 150ms and there is no sliding across the screen, then we define it as a click

Code:

//Encapsulate tap to solve the 300ms delay of click
function tap(obj, callback) {
  var isMove = false;
  var startTime = 0; // Record the time variable when touched
  obj.addEventListener('touchstart', function(e) {
    startTime = Date.now(); // Record touch time
  });
  obj.addEventListener('touchmove', function(e) {
    isMove = true; // See if there is a slide, if there is a slide, it is a drag, not a click
  });
  obj.addEventListener('touchend', function(e) {
    // If the finger touch and leave time is less than 150ms, it is a click
    if (!isMove && (Date.now() - startTime) < 150) { 
      callback && callback(); // Execute the callback function
    }
    isMove = false; // negate reset
    startTime = 0;
  });
}
//transfer
tap(div, function() { // execute code});

(3) Use the plug-in fastclick
Use the fastclick plugin to solve the 300ms delay. Official website: https://github.com/ftlabs/fastclick

1. Introduction
2. Use according to the documentation

For example, in native JS:

if ('addEventListener' in document) {
  document.addEventListener('DOMContentLoaded', function() {
    FastClick.attach(document.body);
  }, false);
}

2. Local storage

1. Overview of local storage

1.1 Background

With the rapid development of the Internet, web-based applications are becoming more common and more complex. In order to meet various needs, a large amount of data is often stored locally. The HTML5 specification proposes related solutions Program.

1.2 Local Storage Features

1. The data is stored in the user's browser
2. Easy to set and read, even page refresh without losing data
3. Large capacity, sessionStorage about 5M, localStorage about 20M
4. Only strings can be stored, and the object can be stored after JSON.stringify() encoding

2. window.sessionStorage

2.1 Features

1. The life cycle is to close the browser window
2. Data can be shared under the same window (page)
3. Store and use in the form of key-value pairs

2.2 Related operations

1. Store data:

sessionStorage.setItem(key, value)

2. Get data:

sessionStorage.getItem(key)

3. Delete data:

sessionStorage.removeItem(key)

4. Delete all data:

sessionStorage.clear()

Code example:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="text">
    <button class="set">Storing data</button>
    <button class="get">retrieve data</button>
    <button class="remove">delete data</button>
    <button class="del">Clear all data</button>
    <script>
        console.log(localStorage.getItem('username'));

        var ipt = document.querySelector('input');
        var set = document.querySelector('.set');
        var get = document.querySelector('.get');
        var remove = document.querySelector('.remove');
        var del = document.querySelector('.del');
        set.addEventListener('click', function() {
            // When we click, we can store the value in the form
            var val = ipt.value;
            sessionStorage.setItem('uname', val);
            sessionStorage.setItem('pwd', val);
        });
        get.addEventListener('click', function() {
            // When we click, we can get the value in the form
            console.log(sessionStorage.getItem('uname'));

        });
        remove.addEventListener('click', function() {
            // 
            sessionStorage.removeItem('uname');

        });
        del.addEventListener('click', function() {
            // When we click, clear all
            sessionStorage.clear();

        });
    </script>
</body>

</html>

3. window.localStorage

3.1 Features

1. The life cycle takes effect permanently, and the closed page will also exist unless it is manually deleted
2. Multiple windows (pages) can be shared (the same browser can share)
3. Store and use in the form of key-value pairs

3.2 Related operations

1. Store data:

localStorage.setItem(key, value)

2. Get data:

localStorage.getItem(key)

3. Delete data:

loaclStorage.removeItem(key)

4. Delete all data:

localStorage.clear()

code:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>

<body>
    <input type="text">
    <button class="set">Storing data</button>
    <button class="get">retrieve data</button>
    <button class="remove">delete data</button>
    <button class="del">Clear all data</button>
    <script>
        var ipt = document.querySelector('input');
        var set = document.querySelector('.set');
        var get = document.querySelector('.get');
        var remove = document.querySelector('.remove');
        var del = document.querySelector('.del');
        set.addEventListener('click', function() {
            var val = ipt.value;
            localStorage.setItem('username', val);
        })
        get.addEventListener('click', function() {
            console.log(localStorage.getItem('username'));

        })
        remove.addEventListener('click', function() {
            localStorage.removeItem('username');

        })
        del.addEventListener('click', function() {
            localStorage.clear();

        })
    </script>
</body>

</html>

4. Case: remember username

4.1 Analysis

If you check Remember Username, the next time the user opens the browser, the last logged-in username will be automatically displayed in the text box.

1. Save the data and use local storage
2. When closing the page, the user name can also be displayed, so localStorage is used
3. Open the page, first judge whether there is this user name, if so, display the user name in the form, and check the check box
4. When the check box changes, the change event
5. If checked, save it, otherwise remove it

4.2 code

<body>
    <input type="text" id="username"> <input type="checkbox" name="" id="remember"> Remember Account Name
    <script>
        var username = document.querySelector('#username');
        var remember = document.querySelector('#remember');
        if (localStorage.getItem('username')) {
            username.value = localStorage.getItem('username');
            remember.checked = true;
        }
        remember.addEventListener('change', function() {
            if (this.checked) {
                localStorage.setItem('username', username.value)
            } else {
                localStorage.removeItem('username');
            }
        })
    </script>
</body>

Tags: Javascript Front-end programming language

Posted by maca134 on Tue, 22 Nov 2022 23:28:51 +0530