APIs series web effects

Posted by dscapuano on Sun, 20 Feb 2022 01:40:37 +0100

catalogue

1, PC side web page effects

1. Element offset offset series

1.1 offset overview

1.2 difference between offset and style

Case: coordinates of the mouse in the box

Case: modal box drag

Case: imitation Jingdong magnifying glass effect

2. Element visual area client series

Case: Taobao flexible JS source code analysis

3. Element scroll series

1. Element scroll series attribute

3.2 the header of the page being rolled away

Case: imitation Taobao fixed right sidebar

3.3 # header compatibility solution for pages being rolled up

4. Summary of three series

5. The difference between mouseenter and mouseover

4, Animation function encapsulation

1. Animation implementation principle

2. Simple encapsulation of animation functions

3. The animation function records different timers for different elements

4. Principle of retarding effect

5. The animation function moves between multiple target values

6. Add callback function to animation function

7. The animation function is encapsulated in a separate JS file

V. common web page special effects cases

Case: Web carousel map

1. Throttle valve

Case: back to top

Case: tendon head cloud case

2, Mobile web effects

          1. Touch screen events

1. Overview of touch screen events

2. Touch event object (TouchEvent)

3. Drag elements at the mobile end

2. Common special effects of mobile terminal

1. classList attribute

Case: mobile terminal rotation map

Case: back to top

2. click delay solution

3. Common development plug-ins of mobile terminal

1. What is a plug-in

2. Use of plug-ins

3. Use of swiper plug-in

4. Common plug-ins of other mobile terminals

5. Usage Summary of plug-ins

6. Exercise - Mobile Video plug-in ZY media. js

4. Common development framework of mobile terminal

1. Framework overview

2. Bootstrap

3, Local storage

1. Local storage

2. window.sessionStorage

3. window.localStorage

Case: remember user name

1, PC side web page effects

1. Element offset offset series

1.1 offset overview

Offset translates to offset. We can dynamically get the position (offset) and size of the element by using the offset series related attributes.

  • Gets the distance of the element from the position with the positioning parent element
  • Gets the size (width, height) of the element itself
  • Note: all returned values do not have units

<!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>
    <style>
        * {
            margin: 0;
            padding: 0;
        }
        
        .father {
            /* position: relative; */
            width: 200px;
            height: 200px;
            background-color: pink;
            margin: 150px;
        }
        
        .son {
            width: 100px;
            height: 100px;
            background-color: purple;
            margin-left: 45px;
        }
        
        .w {
            height: 200px;
            background-color: skyblue;
            margin: 0 auto 200px;
            padding: 10px;
            border: 15px solid red;
        }
    </style>
</head>

<body>
    <div class="father">
        <div class="son"></div>
    </div>
    <div class="w"></div>
    <script>
        // offset series
        var father = document.querySelector('.father');
        var son = document.querySelector('.son');
        // 1. You can get the value without unit returned by the offset position of the element  
        console.log(father.offsetTop);
        console.log(father.offsetLeft);
        // It is subject to the father with positioning. If there is no father or the father has no positioning, it is subject to the body
        console.log(son.offsetLeft);
        var w = document.querySelector('.w');
        // 2. You can get the size, width and height of the element, including padding + border + width 
        console.log(w.offsetWidth);
        console.log(w.offsetHeight);
        // 3. Return the father with location, otherwise return the body
        console.log(son.offsetParent); // Return the father with location, otherwise return the body
        console.log(son.parentNode); // Returning to the father is the closest father. No matter whether the father has a position or not
    </script>
</body>

</html>

1.2 difference between offset and style

<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>
    <style>
        .box {
            width: 200px;
            height: 200px;
            background-color: pink;
            padding: 10px;
        }
    </style>
</head>

<body>
    <div class="box" style="width: 200px;"></div>
    <script>
        // The difference between offset and style
        var box = document.querySelector('.box');
        console.log(box.offsetWidth);
        console.log(box.style.width);
        // box.offsetWidth = '300px';
        box.style.width = '300px';
    </script>
</body>

Case: coordinates of the mouse in the box

 

<!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>
    <style>
        .box {
            width: 300px;
            height: 300px;
            background-color: pink;
            margin: 200px;
        }
    </style>
</head>

<body>
    <div class="box"></div>
    <script>
        // We click in the box to get the distance from the mouse to the left and right of the box.
        // First get the coordinates of the mouse in page. Page (x.page)
        // Secondly, get the distance of the box in the page (box.offsetLeft, box.offsetTop)
        // Subtract the distance of the box in the page from the coordinates of the mouse from the page to obtain the coordinates of the mouse in the box
        var box = document.querySelector('.box');
        box.addEventListener('mousemove', function(e) {
            // console.log(e.pageX);
            // console.log(e.pageY);
            // console.log(box.offsetLeft);
            var x = e.pageX - this.offsetLeft;
            var y = e.pageY - this.offsetTop;
            this.innerHTML = 'x The coordinates are' + x + ' y The coordinates are' + y;
        })
    </script>
</body>

</html>

Case: modal box drag

<!DOCTYPE html>
<html>

<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        .login-header {
            width: 100%;
            text-align: center;
            height: 30px;
            font-size: 24px;
            line-height: 30px;
        }
        
        ul,
        li,
        ol,
        dl,
        dt,
        dd,
        div,
        p,
        span,
        h1,
        h2,
        h3,
        h4,
        h5,
        h6,
        a {
            padding: 0px;
            margin: 0px;
        }
        
        .login {
            display: none;
            width: 512px;
            height: 280px;
            position: fixed;
            border: #ebebeb solid 1px;
            left: 50%;
            top: 50%;
            background: #ffffff;
            box-shadow: 0px 0px 20px #ddd;
            z-index: 9999;
            transform: translate(-50%, -50%);
        }
        
        .login-title {
            width: 100%;
            margin: 10px 0px 0px 0px;
            text-align: center;
            line-height: 40px;
            height: 40px;
            font-size: 18px;
            position: relative;
            cursor: move;
        }
        
        .login-input-content {
            margin-top: 20px;
        }
        
        .login-button {
            width: 50%;
            margin: 30px auto 0px auto;
            line-height: 40px;
            font-size: 14px;
            border: #ebebeb 1px solid;
            text-align: center;
        }
        
        .login-bg {
            display: none;
            width: 100%;
            height: 100%;
            position: fixed;
            top: 0px;
            left: 0px;
            background: rgba(0, 0, 0, .3);
        }
        
        a {
            text-decoration: none;
            color: #000000;
        }
        
        .login-button a {
            display: block;
        }
        
        .login-input input.list-input {
            float: left;
            line-height: 35px;
            height: 35px;
            width: 350px;
            border: #ebebeb 1px solid;
            text-indent: 5px;
        }
        
        .login-input {
            overflow: hidden;
            margin: 0px 0px 20px 0px;
        }
        
        .login-input label {
            float: left;
            width: 90px;
            padding-right: 10px;
            text-align: right;
            line-height: 35px;
            height: 35px;
            font-size: 14px;
        }
        
        .login-title span {
            position: absolute;
            font-size: 12px;
            right: -20px;
            top: -30px;
            background: #ffffff;
            border: #ebebeb solid 1px;
            width: 40px;
            height: 40px;
            border-radius: 20px;
        }
    </style>
</head>

<body>
    <div class="login-header"><a id="link" href="javascript:;">Click to pop up the login box</a></div>
    <div id="login" class="login">
        <div id="title" class="login-title">Login member
            <span><a id="closeBtn" href="javascript:void(0);" class="close-login">close</a></span>
        </div>
        <div class="login-input-content">
            <div class="login-input">
                <label>user name:</label>
                <input type="text" placeholder="enter one user name" name="info[username]" id="username" class="list-input">
            </div>
            <div class="login-input">
                <label>Login password:</label>
                <input type="password" placeholder="Please enter the login password" name="info[password]" id="password" class="list-input">
            </div>
        </div>
        <div id="loginBtn" class="login-button"><a href="javascript:void(0);" id="login-button-submit">Login member</a></div>
    </div>
    <!-- Covering layer -->
    <div id="bg" class="login-bg"></div>
    <script>
        // 1. Get element
        var login = document.querySelector('.login');
        var mask = document.querySelector('.login-bg');
        var link = document.querySelector('#link');
        var closeBtn = document.querySelector('#closeBtn');
        var title = document.querySelector('#title');
        // 2. Click the pop-up layer link to display the mask and login
        link.addEventListener('click', function() {
                mask.style.display = 'block';
                login.style.display = 'block';
            })
            // 3. Click closeBtn to hide mask and login 
        closeBtn.addEventListener('click', function() {
                mask.style.display = 'none';
                login.style.display = 'none';
            })
            // 4. Start dragging
            // (1) When we press the mouse, we get the coordinates of the mouse in the box
        title.addEventListener('mousedown', function(e) {
            var x = e.pageX - login.offsetLeft;
            var y = e.pageY - login.offsetTop;
            // (2) When the mouse moves, subtract the coordinates of the mouse in the box from the coordinates of the mouse in the page to obtain the left and top values of the modal box
            document.addEventListener('mousemove', move)

            function move(e) {
                login.style.left = e.pageX - x + 'px';
                login.style.top = e.pageY - y + 'px';
            }
            // (3) When the mouse pops up, the mouse movement event is removed
            document.addEventListener('mouseup', function() {
                document.removeEventListener('mousemove', move);
            })
        })
    </script>
</body>

</html>

Case: imitation Jingdong magnifying glass effect

window.addEventListener('load', function() {
    var preview_img = document.querySelector('.preview_img');
    var mask = document.querySelector('.mask');
    var big = document.querySelector('.big');
    // 1. When we mouse over preview_img shows and hides mask occlusion layer and big box
    preview_img.addEventListener('mouseover', function() {
        mask.style.display = 'block';
        big.style.display = 'block';
    })
    preview_img.addEventListener('mouseout', function() {
            mask.style.display = 'none';
            big.style.display = 'none';
        })
        // 2. When the mouse moves, let the yellow box follow the mouse
    preview_img.addEventListener('mousemove', function(e) {
        // (1).  First calculate the coordinates of the mouse in the box
        var x = e.pageX - this.offsetLeft;
        var y = e.pageY - this.offsetTop;
        // console.log(x, y);
        // (2) Subtracting half of the box height of 300 is 150, which is the final left and top values of our mask
        // (3) The distance we mask
        var maskX = x - mask.offsetWidth / 2;
        var maskY = y - mask.offsetHeight / 2;
        // (4) If the x coordinate is less than 0, let him stop at 0
        // Maximum movement distance of occlusion layer
        var maskMax = preview_img.offsetWidth - mask.offsetWidth;
        if (maskX <= 0) {
            maskX = 0;
        } else if (maskX >= maskMax) {
            maskX = maskMax;
        }
        if (maskY <= 0) {
            maskY = 0;
        } else if (maskY >= maskMax) {
            maskY = maskMax;
        }
        mask.style.left = maskX + 'px';
        mask.style.top = maskY + 'px';
        // 3. Moving distance of large picture = moving distance of occlusion layer * maximum moving distance of large picture / maximum moving distance of occlusion layer
        // Big picture
        var bigIMg = document.querySelector('.bigImg');
        // Maximum moving distance of large picture
        var bigMax = bigIMg.offsetWidth - big.offsetWidth;
        // Moving distance of large picture X Y
        var bigX = maskX * bigMax / maskMax;
        var bigY = maskY * bigMax / maskMax;
        bigIMg.style.left = -bigX + 'px';
        bigIMg.style.top = -bigY + 'px';

    })

})

2. Element visual area client series

Client is translated as the client. We use the relevant attributes of the {client series to obtain the relevant information of the element visual area. The border size and element size of the element can be dynamically obtained through the relevant attributes of the client series.

Case: Taobao flexible JS source code analysis

Immediate execution function (function() {}) () or (function() {} ()) main function: create a separate scope. Avoid naming conflicts

The following three cases will refresh the page and trigger the load event.

  1. a hyperlink to tag
  2. F5 or refresh button (forced refresh)
  3. Forward and backward buttons

However, there is a feature in Firefox. There is a "round-trip cache". This cache not only saves page data, but also saves the state of DOM and JavaScript; In fact, the whole page is saved in memory.

Therefore, the back button cannot refresh the page at this time.

At this point, you can use the pageshow event to trigger., This event is triggered when the page is displayed, whether or not the page is from the cache. In the reload page, pageshow will be triggered after the load event is triggered; Judge whether it is the pageshow event triggered by the page in the cache according to the persisted in the event object. Note that this event is added to the window.  

(function flexible(window, document) {
    // Gets the root element of the html
    var docEl = document.documentElement
        // dpr physical pixel ratio
    var dpr = window.devicePixelRatio || 1

    // adjust body font size sets the font size of our body
    function setBodyFontSize() {
        // If there is a body element in the page, set the font size of the body
        if (document.body) {
            document.body.style.fontSize = (12 * dpr) + 'px'
        } else {
            // If there is no body element in the page, wait until the main DOM elements of our page are loaded before setting the body
            // Font size
            document.addEventListener('DOMContentLoaded', setBodyFontSize)
        }
    }
    setBodyFontSize();

    // set 1rem = viewWidth / 10 set the text size of our html elements
    function setRemUnit() {
        var rem = docEl.clientWidth / 10
        docEl.style.fontSize = rem + 'px'
    }

    setRemUnit()

    // reset rem unit on page resize when our page size changes, we need to reset the size of the next rem
    window.addEventListener('resize', setRemUnit)
        // pageshow is the event triggered when we reload the page
    window.addEventListener('pageshow', function(e) {
        // e. Persistent returns true, which means that if the page is taken from the cache, you also need to recalculate the size of rem
        if (e.persisted) {
            setRemUnit()
        }
    })

    // detect 0.5px supports some mobile browsers do not support 0.5 pixel writing
    if (dpr >= 2) {
        var fakeBody = document.createElement('body')
        var testElement = document.createElement('div')
        testElement.style.border = '.5px solid transparent'
        fakeBody.appendChild(testElement)
        docEl.appendChild(fakeBody)
        if (testElement.offsetHeight === 1) {
            docEl.classList.add('hairlines')
        }
        docEl.removeChild(fakeBody)
    }
}(window, document))

 3. Element scroll series

1. Element scroll series attribute

Scroll translates to scrolling. We can dynamically get the size and scrolling distance of the element by using the relevant attributes of the scroll series.  

3.2 the header of the page being rolled away

If the height (or width) of the browser is not enough to display the whole page, the scroll bar will appear automatically. When the scroll bar scrolls down, the height of the hidden top of the page is called the head of the page. The onscroll event is triggered when the scroll bar scrolls.

Size of scrollTop

Is the distance from the inner edge of the top border to the top of the content

Case: imitation Taobao fixed right sidebar

1. The original sidebar was absolute positioning

2. When the page scrolls to a certain position, the sidebar changes to fixed positioning

3. If the page continues to scroll, it will be displayed at the top

<!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>
    <style>
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }
        
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        
        .header {
            height: 150px;
            background-color: purple;
        }
        
        .banner {
            height: 250px;
            background-color: skyblue;
        }
        
        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
        
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">Back to top</span>
    </div>
    <div class="header w">Head area</div>
    <div class="banner w">banner region</div>
    <div class="main w">Main part</div>
    <script>
        //1. Get element
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        // banner.offestTop is the size of the rolled head, which must be written outside the scroll
        var bannerTop = banner.offsetTop
            // The value that should change when we fix the positioning of the sidebar
        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        // Get main body element
        var main = document.querySelector('.main');
        var goBack = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        // 2. Page scrolling event scroll
        document.addEventListener('scroll', function() {
            // console.log(11);
            // window.pageYOffset the header of the page being rolled out
            // console.log(window.pageYOffset);
            // 3 . When the header of our page is greater than or equal to 172, the sidebar will be changed to fixed positioning
            if (window.pageYOffset >= bannerTop) {
                sliderbar.style.position = 'fixed';
                sliderbar.style.top = sliderbarTop + 'px';
            } else {
                sliderbar.style.position = 'absolute';
                sliderbar.style.top = '300px';
            }
            // 4. When our page scrolls to the main box, the goback module is displayed
            if (window.pageYOffset >= mainTop) {
                goBack.style.display = 'block';
            } else {
                goBack.style.display = 'none';
            }

        })
    </script>
</body>

</html>

3.3 # header compatibility solution for pages being rolled up

It should be noted that there is a compatibility problem with the rolled head of the page. Therefore, the rolled head is usually written in the following ways:

1. Declare DTD and use document documentElement. scrollTop

2. If DTD is not declared, use # document body. scrollTop

3. New method window Pageyoffset and window Pagexoffset, supported by IE9

 4. Summary of three series

Their main usage:

  • The offset series is often used to obtain the element position {offsetLeft} offsetTop
  • client is often used to get element size, clientWidth, clientHeight
  • scroll is often used to obtain the scrollTop scrollLeft
  • Notice how far the page scrolls through the window Pagexoffset get

5. The difference between mouseenter and mouseover

mouseenter mouse event

  • The mouseenter event is triggered when the mouse moves over the element
  • Similar to mouseover, the difference between them is
  • mouseover mouse will trigger when it passes through its own box and sub box. mouseenter # can only be triggered through its own box
  • This is because mouseenter doesn't bubble
  • With mouseenter, the mouse will not bubble when leaving mouseleave

4, Animation function encapsulation

1. Animation implementation principle

Core principle: continuously move the box position through the timer setInterval().  

Implementation steps:

  1. Get the current position of the box
  2. Add 1 movement distance to the current position of the box
  3. Use the timer to repeat this operation continuously
  4. Add a condition to end the timer
  5. Note that this element needs to add positioning before you can use element style. left
<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>
    <style>
        div {
            position: absolute;   //Be sure to add positioning (here is absolute positioning)
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
    </style>
</head>

<body>
    <div></div>
    <script>
        // Animation principle
        // 1. Get the current position of the box  
        // 2. Add 1 movement distance to the current position of the box
        // 3. Use the timer to repeat this operation continuously
        // 4. Add a condition to end the timer
        // 5. Note that this element needs to add positioning before it can be used style. left
        var div = document.querySelector('div');
        var timer = setInterval(function () {
            if (div.offsetLeft >= 400) {
                // The essence of stopping animation is to stop the timer
                clearInterval(timer);
            }
            div.style.left = div.offsetLeft + 1 + 'px';   //offsetLeft can only be obtained and cannot be assigned
        }, 30);
    </script>
</body>

2. Simple encapsulation of animation functions

Note that the function needs to pass two parameters, the animated object and the distance to move.  

<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>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        
        span {
            position: absolute;
            left: 0;
            top: 200px;
            display: block;
            width: 150px;
            height: 150px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <div></div>
    <span>Xia Yuhe</span>
    <script>
        // Simple animation function encapsulates obj target object target position
        function animate(obj, target) {
            var timer = setInterval(function() {
                if (obj.offsetLeft >= target) {
                    // The essence of stopping animation is to stop the timer
                    clearInterval(timer);
                }
                obj.style.left = obj.offsetLeft + 1 + 'px';

            }, 30);
        }

        var div = document.querySelector('div');
        var span = document.querySelector('span');
        // Call function
        animate(div, 300);
        animate(span, 200);
    </script>
</body>

3. The animation function records different timers for different elements

If multiple elements use this animation function, var should declare the timer every time. We can use different timers for different elements (we use our own timers).

Core principle: JS is a dynamic language, which can easily add attributes to the current object.  

<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>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        
        span {
            position: absolute;
            left: 0;
            top: 200px;
            display: block;
            width: 150px;
            height: 150px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <button>Click Xia Yuhe to leave</button>
    <div></div>
    <span>Xia Yuhe</span>
    <script>
        // var obj = {};
        // obj.name = 'andy';
        // Simple animation function encapsulates obj target object target position
        // Different timers are assigned to different elements
        function animate(obj, target) {
            // When we keep clicking on the button, the speed of this element will be faster and faster, because too many timers are turned on
            // The solution is to let our element have only one timer to execute
            // First clear the previous timer and only keep the current timer for execution
            clearInterval(obj.timer);
            obj.timer = setInterval(function() {
                if (obj.offsetLeft >= target) {
                    // The essence of stopping animation is to stop the timer
                    clearInterval(obj.timer);
                }
                obj.style.left = obj.offsetLeft + 1 + 'px';

            }, 30);
        }

        var div = document.querySelector('div');
        var span = document.querySelector('span');
        var btn = document.querySelector('button');
        // Call function
        animate(div, 300);
        btn.addEventListener('click', function() {
            animate(span, 200);
        })
    </script>
</body>

4. Principle of retarding effect

Slow motion animation is to change the movement speed of elements. The most common is to stop the speed slowly

Idea:

  1. Let the distance of each movement of the box slowly decrease, and the speed will slowly fall down.
  2. Core algorithm: (target value - current position) / 10 ¢ as the distance step of each movement
  3. The condition for stopping is to stop the timer when the current box position is equal to the target position
  4. Note that the step value needs to be rounded
<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>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        
        span {
            position: absolute;
            left: 0;
            top: 200px;
            display: block;
            width: 150px;
            height: 150px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <button>Click Xia Yuhe to leave</button>
    <span>Xia Yuhe</span>
    <script>
        // Jog animation function encapsulates obj target object target position
        // Idea:
        // 1. Let the distance of each movement of the box slowly decrease, and the speed will slowly fall down.
        // 2. Core algorithm: (target value - current position) / 10 as the distance step of each movement
        // 3. Stop condition: stop the timer when the current box position is equal to the target position
        function animate(obj, target) {
            // First clear the previous timer and only keep the current timer for execution
            clearInterval(obj.timer);
            obj.timer = setInterval(function() {
                // The step value is written into the timer
                var step = (target - obj.offsetLeft) / 10;
                if (obj.offsetLeft == target) {
                    // The essence of stopping animation is to stop the timer
                    clearInterval(obj.timer);
                }
                // Change the step value of adding 1 each time to a slowly decreasing value step formula: (target value - current position) / 10
                obj.style.left = obj.offsetLeft + step + 'px';

            }, 15);
        }
        var span = document.querySelector('span');
        var btn = document.querySelector('button');

        btn.addEventListener('click', function() {
                // Call function
                animate(span, 500);
            })
            // Uniform animation means that the box is the current position + a fixed value of 10 
            // Jog animation is the current position of the box + the changed value (target value - current position) / 10)
    </script>
</body>

5. The animation function moves between multiple target values

You can move animation functions from 800 to 500.

When we click the button, we judge whether the step size is positive or negative

  1. If it is a positive value, the step size is rounded to the larger one
  2. If it is negative, the step size is rounded down
<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>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }

        span {
            position: absolute;
            left: 0;
            top: 200px;
            display: block;
            width: 150px;
            height: 150px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <button class="btn500">Click Xia Yuhe to 500</button>
    <button class="btn800">Click Xia Yuhe to 800</button>
    <span>Xia Yuhe</span>
    <script>
        // Jog animation function encapsulates obj target object target position
        // Idea:
        // 1. Let the distance of each movement of the box slowly decrease, and the speed will slowly fall down.
        // 2. Core algorithm: (target value - current position) / 10 as the distance step of each movement
        // 3. Stop condition: stop the timer when the current box position is equal to the target position
        function animate(obj, target) {
            // First clear the previous timer and only keep the current timer for execution
            clearInterval(obj.timer);
            obj.timer = setInterval(function () {
                // The step value is written into the timer
                // Let's change the step value to an integer to avoid the problem of decimals
                // var step = Math.ceil((target - obj.offsetLeft) / 10);   // Math.ceil() rounded up (large)
                var step = (target - obj.offsetLeft) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);    //  Math.floor() rounded down (small)
                if (obj.offsetLeft == target) {
                    // The essence of the timer is to stop the animation
                    clearInterval(obj.timer);
                }
                // Change the step value of adding 1 each time to a slowly decreasing value step formula: (target value - current position) / 10
                obj.style.left = obj.offsetLeft + step + 'px';

            }, 15);
        }
        var span = document.querySelector('span');
        var btn500 = document.querySelector('.btn500');
        var btn800 = document.querySelector('.btn800');

        btn500.addEventListener('click', function () {
            // Call function
            animate(span, 500);
        })
        btn800.addEventListener('click', function () {
            // Call function
            animate(span, 800);
        })
            // Uniform animation means that the box is the current position + a fixed value of 10
            // Jog animation is the current position of the box + the changed value (target value - current position) / 10)
    </script>
</body>

 6. Add callback function to animation function

Callback function principle: function can be used as a parameter. Pass this function as a parameter to another function. When that function is executed, execute the passed function. This process is called callback.

Write position of callback function: the position where the timer ends.  

<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>
    <style>
        div {
            position: absolute;
            left: 0;
            width: 100px;
            height: 100px;
            background-color: pink;
        }
        
        span {
            position: absolute;
            left: 0;
            top: 200px;
            display: block;
            width: 150px;
            height: 150px;
            background-color: purple;
        }
    </style>
</head>

<body>
    <button class="btn500">Click Xia Yuhe to 500</button>
    <button class="btn800">Click Xia Yuhe to 800</button>
    <span>Xia Yuhe</span>
    <script>
        // Jog animation function encapsulates obj target object target position
        // Idea:
        // 1. Let the distance of each movement of the box slowly decrease, and the speed will slowly fall down.
        // 2. Core algorithm: (target value - current position) / 10 as the distance step of each movement
        // 3. Stop condition: stop the timer when the current box position is equal to the target position
        function animate(obj, target, callback) {
            // console. log(callback);   Callback = callback() when function() {} is called

            // First clear the previous timer and only keep the current timer for execution
            clearInterval(obj.timer);
            obj.timer = setInterval(function() {
                // The step value is written into the timer
                // Let's change the step value to an integer to avoid the problem of decimals
                // var step = Math.ceil((target - obj.offsetLeft) / 10);
                var step = (target - obj.offsetLeft) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (obj.offsetLeft == target) {
                    // The essence of the timer is to stop the animation
                    clearInterval(obj.timer);
                    // The callback function is written to the end of the timer
                    if (callback) {
                        // Call function
                        callback();
                    }
                }
                // Change the step value of adding 1 each time to a slowly decreasing value step formula: (target value - current position) / 10
                obj.style.left = obj.offsetLeft + step + 'px';

            }, 15);
        }
        var span = document.querySelector('span');
        var btn500 = document.querySelector('.btn500');
        var btn800 = document.querySelector('.btn800');

        btn500.addEventListener('click', function() {
            // Call function
            animate(span, 500);
        })
        btn800.addEventListener('click', function() {
                // Call function
                animate(span, 800, function() {
                    // alert('How are you ');
                    span.style.backgroundColor = 'red';
                });
            })
            // Uniform animation means that the box is the current position + a fixed value of 10 
            // Jog animation is the current position of the box + the changed value (target value - current position) / 10)
    </script>
</body>

7. The animation function is encapsulated in a separate JS file

Because this animation function is often used in the future, it can be encapsulated in a JS file separately, and the JS file can be referenced when using it.

  1. Create a new JS file separately.
  2. HTML files are imported into JS files.

 1. Create a new JS file separately

function animate(obj, target, callback) {
    // console. log(callback);   Callback = callback() when function() {} is called

    // First clear the previous timer and only keep the current timer for execution
    clearInterval(obj.timer);
    obj.timer = setInterval(function() {
        // The step value is written into the timer
        // Let's change the step value to an integer to avoid the problem of decimals
        // var step = Math.ceil((target - obj.offsetLeft) / 10);
        var step = (target - obj.offsetLeft) / 10;
        step = step > 0 ? Math.ceil(step) : Math.floor(step);
        if (obj.offsetLeft == target) {
            // The essence of the timer is to stop the animation
            clearInterval(obj.timer);
            // The callback function is written to the end of the timer
            // if (callback) {
            //     //Call function
            //     callback();
            // }
            callback && callback();
        }
        // Change the step value of adding 1 each time to a slowly decreasing value step formula: (target value - current position) / 10
        obj.style.left = obj.offsetLeft + step + 'px';

    }, 15);
}

2. Import HTML file.

<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>
    <style>
        .sliderbar {
            position: fixed;
            right: 0;
            bottom: 100px;
            width: 40px;
            height: 40px;
            text-align: center;
            line-height: 40px;
            cursor: pointer;
            color: #fff;
        }
        
        .con {
            position: absolute;
            left: 0;
            top: 0;
            width: 200px;
            height: 40px;
            background-color: purple;
            z-index: -1;
        }
    </style>
    <script src="animate.js"></script>
</head>

<body>
    <div class="sliderbar">
        <span>←</span>
        <div class="con">Problem feedback</div>
    </div>

    <script>
        // 1. Get element
        var sliderbar = document.querySelector('.sliderbar');
        var con = document.querySelector('.con');
        // When we mouse over the sliderbar, we will let the con box slide to the left
        // When we move the mouse away from the sliderbar, we will let the con box slide to the right
        sliderbar.addEventListener('mouseenter', function() {
            // animate(obj, target, callback);
            animate(con, -160, function() {
                // When we finish the animation, change ← to →
                sliderbar.children[0].innerHTML = '→';
            });

        })
        sliderbar.addEventListener('mouseleave', function() {
            // animate(obj, target, callback);
            animate(con, 0, function() {
                sliderbar.children[0].innerHTML = '←';
            });

        })
    </script>
</body>

V. common web page special effects cases

Case: Web carousel map

 

 

window.addEventListener('load', function() {
    // 1. Get element
    var arrow_l = document.querySelector('.arrow-l');
    var arrow_r = document.querySelector('.arrow-r');
    var focus = document.querySelector('.focus');
    var focusWidth = focus.offsetWidth;
    // 2. After the mouse passes focus, the left and right buttons will be displayed and hidden
    focus.addEventListener('mouseenter', function() {
        arrow_l.style.display = 'block';
        arrow_r.style.display = 'block';
        clearInterval(timer);
        timer = null; // Clear timer variable
    });
    focus.addEventListener('mouseleave', function() {
        arrow_l.style.display = 'none';
        arrow_r.style.display = 'none';
        timer = setInterval(function() {
            //Manually call click event
            arrow_r.click();
        }, 2000);
    });
    // 3. Dynamically generate small circles. If there are several pictures, I will generate several small circles
    var ul = focus.querySelector('ul');
    var ol = focus.querySelector('.circle');
    // console.log(ul.children.length);
    for (var i = 0; i < ul.children.length; i++) {
        // Create a small li 
        var li = document.createElement('li');
        // The index number of the current small circle is recorded through the user-defined attribute 
        li.setAttribute('index', i);
        // Insert small li into ol
        ol.appendChild(li);
        // 4. Exclusive thought of small circles. We can directly bind click events while generating small circles
        li.addEventListener('click', function() {
            // Kill everyone and clear all small li current class names
            for (var i = 0; i < ol.children.length; i++) {
                ol.children[i].className = '';
            }
            // Leave my current little li and set the current class name
            this.className = 'current';
            // 5. Click on the small circle to move the picture. Of course, the picture is ul 
            // ul's moving distance the index number of the small circle times the width of the picture. Note that it is a negative value
            // When we click a small li, we get the index number of the current small li
            var index = this.getAttribute('index');
            // When we click a small li, we need to give the index number of the li to num  
            num = index;
            // When we click on a small li, we need to give the index number of the li to the circle  
            circle = index;
            // num = circle = index;
            console.log(focusWidth);
            console.log(index);

            animate(ul, -index * focusWidth);
        })
    }
    // Set the first small li in ol to the class name current
    ol.children[0].className = 'current';
    // 6. Clone the first picture (li) and put it at the back of ul
    var first = ul.children[0].cloneNode(true);
    ul.appendChild(first);
    // 7. Click the button on the right to scroll one picture
    var num = 0;
    // circle controls the playback of small circles
    var circle = 0;
    // flag throttle valve
    var flag = true;
    arrow_r.addEventListener('click', function() {
        if (flag) {
            flag = false; // Close the throttle valve
            // If we get to the last copied picture, our ul should quickly recover and change left to 0
            if (num == ul.children.length - 1) {
                ul.style.left = 0;
                num = 0;
            }
            num++;
            animate(ul, -num * focusWidth, function() {
                flag = true; // Open the throttle valve
            });
            // 8. Click the button on the right and the small circle will change together. You can declare another variable to control the playback of the small circle
            circle++;
            // If circle == 4, it means that at the end, we cloned the picture, and we will restore it
            if (circle == ol.children.length) {
                circle = 0;
            }
            // Call function
            circleChange();
        }
    });

    // 9. Method of left button
    arrow_l.addEventListener('click', function() {
        if (flag) {
            flag = false;
            if (num == 0) {
                num = ul.children.length - 1;
                ul.style.left = -num * focusWidth + 'px';

            }
            num--;
            animate(ul, -num * focusWidth, function() {
                flag = true;
            });
            // Click the button on the left and the small circle will change together. You can declare another variable to control the playback of the small circle
            circle--;
            // If circle < 0 indicates the first picture, the small circle should be changed to the fourth small circle (3)
            // if (circle < 0) {
            //     circle = ol.children.length - 1;
            // }
            circle = circle < 0 ? ol.children.length - 1 : circle;
            // Call function
            circleChange();
        }
    });

    function circleChange() {
        // First clear the current class name of the remaining small circles
        for (var i = 0; i < ol.children.length; i++) {
            ol.children[i].className = '';
        }
        // Leave the current class name of the current small circle
        ol.children[circle].className = 'current';
    }
    // 10. Automatically play the rotation chart
    var timer = setInterval(function() {
        //Manually call click event
        arrow_r.click();
    }, 2000);

})

1. Throttle valve

Prevent the rotation chart button from playing too fast due to continuous clicking.

Purpose of throttle valve: when the content of the previous function animation is executed, execute the next function animation, so that the event cannot be triggered continuously.

Core implementation idea: use the callback function to add a variable to control, lock and unlock the function.

Start setting a variable var flag = true;

If(flag) {flag = false; do something} turn off the tap

After the animation is executed by using the callback function, flag = true = turn on the faucet

Case: back to top

Scroll the window to a specific location in the document.

window.scroll(x, y)

Note that the x and y in it don't follow the unit. Write the number directly

case analysis

  • Return to top with animation
  • At this point, we can continue to use our encapsulated animation functions
  • Just change all the left related values to be related to the vertical scrolling distance of the page
  • How much page scrolls can be through window Pageyoffset
  • Finally, page scrolling, using window scroll(x,y) 
<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>
    <style>
        .slider-bar {
            position: absolute;
            left: 50%;
            top: 300px;
            margin-left: 600px;
            width: 45px;
            height: 130px;
            background-color: pink;
        }
        
        .w {
            width: 1200px;
            margin: 10px auto;
        }
        
        .header {
            height: 150px;
            background-color: purple;
        }
        
        .banner {
            height: 250px;
            background-color: skyblue;
        }
        
        .main {
            height: 1000px;
            background-color: yellowgreen;
        }
        
        span {
            display: none;
            position: absolute;
            bottom: 0;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">Back to top</span>
    </div>
    <div class="header w">Head area</div>
    <div class="banner w">banner region</div>
    <div class="main w">Main part</div>
    <script>
        //1. Get element
        var sliderbar = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');
        // banner.offestTop is the size of the rolled head, which must be written outside the scroll
        var bannerTop = banner.offsetTop
            // The value that should change when we fix the positioning of the sidebar
        var sliderbarTop = sliderbar.offsetTop - bannerTop;
        // Get main body element
        var main = document.querySelector('.main');
        var goBack = document.querySelector('.goBack');
        var mainTop = main.offsetTop;
        // 2. Page scrolling event scroll
        document.addEventListener('scroll', function() {
                // console.log(11);
                // window.pageYOffset the header of the page being rolled out
                // console.log(window.pageYOffset);
                // 3 . When the header of our page is greater than or equal to 172, the sidebar will be changed to fixed positioning
                if (window.pageYOffset >= bannerTop) {
                    sliderbar.style.position = 'fixed';
                    sliderbar.style.top = sliderbarTop + 'px';
                } else {
                    sliderbar.style.position = 'absolute';
                    sliderbar.style.top = '300px';
                }
                // 4. When our page scrolls to the main box, the goback module is displayed
                if (window.pageYOffset >= mainTop) {
                    goBack.style.display = 'block';
                } else {
                    goBack.style.display = 'none';
                }

            })
            // 3. When we click the back to top module, let the window scroll to the top of the page
        goBack.addEventListener('click', function() {
            // The x and y in it don't follow the unit, just write the number directly
            // window.scroll(0, 0);
            // Because it is window scrolling, the object is window
            animate(window, 0);
        });
        // Animation function
        function animate(obj, target, callback) {
            // console. log(callback);   Callback = callback() when function() {} is called

            // First clear the previous timer and only keep the current timer for execution
            clearInterval(obj.timer);
            obj.timer = setInterval(function() {
                // The step value is written into the timer
                // Let's change the step value to an integer to avoid the problem of decimals
                // var step = Math.ceil((target - obj.offsetLeft) / 10);
                var step = (target - window.pageYOffset) / 10;
                step = step > 0 ? Math.ceil(step) : Math.floor(step);
                if (window.pageYOffset == target) {
                    // The essence of the timer is to stop the animation
                    clearInterval(obj.timer);
                    // The callback function is written to the end of the timer
                    // if (callback) {
                    //     //Call function
                    //     callback();
                    // }
                    callback && callback();
                }
                // Change the step value of adding 1 each time to a slowly decreasing value step formula: (target value - current position) / 10
                // obj.style.left = window.pageYOffset + step + 'px';
                window.scroll(0, window.pageYOffset + step);
            }, 15);
        }
    </script>
</body>

Case: tendon head cloud case

  • When the mouse passes a small li, the tumbling cloud follows it to the current small li position
  • The mouse leaves this small li, and the tumbling cloud returns to its original position
  • Click a small li with the mouse, and the tumbling cloud will stay at the position where you click the small li

Case analysis

  1. Using animation function to do animation effect
  2. The original starting position of the tumbling cloud was 0
  3. When the mouse passes a small li, take the offsetLeft position of the current small li as the target value
  4. When the mouse leaves a small li, set the target value to 0
  5. If you click a small li, the current position of li will be stored as the starting position of the somersault cloud
<script src="animate.js"></script>
    <script>
        window.addEventListener('load', function() {
            // 1. Get element
            var cloud = document.querySelector('.cloud');
            var c_nav = document.querySelector('.c-nav');
            var lis = c_nav.querySelectorAll('li');
            // 2. Bind events to all small li 
            // This current is used as the starting position of the somersault cloud
            var current = 0;
            for (var i = 0; i < lis.length; i++) {
                // (1) After the mouse passes, take the position of the current small li as the target value
                lis[i].addEventListener('mouseenter', function() {
                    animate(cloud, this.offsetLeft);
                });
                // (2) When the mouse leaves, it returns to the starting position 
                lis[i].addEventListener('mouseleave', function() {
                    animate(cloud, current);
                });
                // (3) When we click the mouse, we will take the current position as the target value
                lis[i].addEventListener('click', function() {
                    current = this.offsetLeft;
                });
            }
        })
    </script>
</head>

2, Mobile web effects

1. Touch screen events

1. Overview of touch screen events

The mobile browser has good compatibility. We don't need to consider the compatibility of previous JS. We can safely use the native JS writing effect, but the mobile terminal also has its own unique features. For example, touch (also known as touch event), Android and IOS have both.

The touch object represents a touch point. The touch point may be a finger or a stylus. Touch screen events can respond to the user's finger (or stylus) operation on the screen or touchpad.  

Common touch screen events are as follows:

<body>
    <div></div>
    <script>
        // 1. Get element
        // 2. Event of finger touching DOM element
        var div = document.querySelector('div');
        div.addEventListener('touchstart', function() {
            console.log('I touched the screen');

        });
        // 3. Finger movement event on DOM element
        div.addEventListener('touchmove', function() {
            console.log('Continue to touch the screen');

        });
        // 4. Event of finger leaving DOM element
        div.addEventListener('touchend', function() {
            console.log('Left the screen');

        });
    </script>
</body>

2. Touch event object (TouchEvent)

TouchEvent is a kind of event that describes the state change of fingers on the touch plane (touch screen, touch pad, etc.). Such events are used to describe one or more contacts, so that developers can detect the movement of contacts, the increase and decrease of contacts, and so on

touchstart, touchmove and touchend all have their own event objects.  

Touch the event object. Let's focus on three common object lists:

Because we usually register touch events for elements, we should remember targetTocuhes

 <div></div>
    <script>
        // Touch event object
        // 1. Get element
        // 2. Event of finger touching DOM element
        var div = document.querySelector('div');
        div.addEventListener('touchstart', function(e) {
            // console.log(e);
            // touches is touching a list of all fingers on the screen 
            // targetTouches is touching the finger list of the current DOM element
            // If you are listening for a DOM element, they are the same
            // changedTouches the list of finger states that have changed from nothing to something or from something to nothing
            // Because we usually touch elements, targetTouches are most often used
            console.log(e.targetTouches[0]);
            // targetTouches[0] can get the relevant information of the first finger touching the dom element, such as the coordinates of the finger and so on


        });
        // 3. Finger movement event on DOM element
        div.addEventListener('touchmove', function() {


        });
        // 4. Event of finger leaving DOM element
        div.addEventListener('touchend', function(e) {
            // console.log(e);
            // When our fingers leave the screen, there is no list of touches and targetTouches
            // But there will be changedTouches


        });
    </script>

3. Drag elements at the mobile end

  1. touchstart, touchmove and touchend can drag elements
  2. However, dragging an element requires the coordinate value of the current finger. We can use pageX and pageY in targetTouches[0]
  3. Principle of moving end dragging: during finger movement, calculate the distance of finger movement. Then use the original position of the box + the distance moved by your fingers
  4. Finger movement distance: the position in the finger sliding minus the position where the finger just started to touch

Drag element Trilogy:

(1) Touch element touchstart: obtain 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:

Note: finger movement will also trigger screen scrolling, so the default screen scrolling e.preventDefault();

<body>
    <div></div>
    <script>
        // (1) Touch element touchstart: obtain 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 moving 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 the fingers move
            this.style.left = x + moveX + 'px';
            this.style.top = y + moveY + 'px';
            e.preventDefault(); // Default behavior to prevent screen scrolling
        });
    </script>
</body>

2. Common special effects of mobile terminal

1. classList attribute

The classList attribute is a new attribute in HTML5, which returns the class name of the element. However, ie10 and above support.

This attribute is used to add, remove and switch CSS classes in the element. There are the following methods

Add class:

element.classList.add ('class name ');  

 

Remove class:

element.classList.remove ('class name ');

Switching class:

element.classList.toggle ('class name ');

Note that in the above methods, all class names do not contain dots

<!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>
    <style>
        .bg {
            background-color: black;
        }
    </style>
</head>

<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 add a class name after it. It will not overwrite the previous class name. Note that it is not necessary to add a class name before it
        div.classList.add('three');
        // 2. Delete class name
        div.classList.remove('one');
        // 3. Switching class
        var btn = document.querySelector('button');
        btn.addEventListener('click', function() {
            document.body.classList.toggle('bg');
        })
    </script>
</body>

</html>

Case: mobile terminal rotation map

The rotation chart function of the mobile terminal is consistent with that of the basic PC terminal.

  1. Can automatically play pictures
  2. You can drag your finger to play the carousel

Case analysis

  1. Auto play function
  2. Start timer
  3. When the mobile end moves, you can use translate to move
  4. If you want the picture to move gracefully, please add a transition effect

 

 

 

Case: back to top

  

window.addEventListener('load', function () {
    // alert(1);
    // 1. Get element 
    var focus = document.querySelector('.focus');
    var ul = focus.children[0];
    // Get the width of focus
    var w = focus.offsetWidth;
    var ol = focus.children[1];
    // 2. Use the timer to automatically rotate the pictures
    var index = 0;
    var timer = setInterval(function () {
        index++;
        var translatex = -index * w;
        ul.style.transition = 'all .3s';   // c3 transition effect, no need to write pc animation
        ul.style.transform = 'translateX(' + translatex + 'px)';
    }, 2000);
    // After the transition is completed, we can judge and monitor the transition end of the transition 
    ul.addEventListener('transitionend', function () {
        // Seamless rolling
        if (index >= 3) {
            index = 0;
            // console.log(index);
            // Remove the transition effect, so that our ul can jump to the target position quickly
            ul.style.transition = 'none';
            // Use the latest index number multiplied by the width to scroll the picture
            var translatex = -index * w;
            ul.style.transform = 'translateX(' + translatex + 'px)';
        } else if (index < 0) {
            index = 2;
            ul.style.transition = 'none';
            // Use the latest index number multiplied by the width to scroll the picture
            var translatex = -index * w;
            ul.style.transform = 'translateX(' + translatex + 'px)';
        }
        // 3. Small dots follow the change
        // Select the li with the current class name in ol and remove the class name remove
        ol.querySelector('.current').classList.remove('current');
        // Add current add to the small li of the current index number
        ol.children[index].classList.add('current');
    });

    // 4. Finger sliding rotation chart 
    // Touch element touchstart: get the initial coordinates of the finger
    var startX = 0;
    var moveX = 0; // We will use this moving distance later, so we need to define a global variable
    var flag = false;
    ul.addEventListener('touchstart', function (e) {
        startX = e.targetTouches[0].pageX;
        // Stop the timer when your finger touches it
        clearInterval(timer);
    });
    // Move the finger touchmove: calculate the sliding distance of the finger and move the box
    ul.addEventListener('touchmove', function (e) {
        // Calculate the moving distance
        moveX = e.targetTouches[0].pageX - startX;
        // Move the box: the original position of the box + the distance the finger moves 
        var translatex = -index * w + moveX;
        // When you drag with your fingers, you don't need animation effect, so you need to cancel the transition effect
        ul.style.transition = 'none';
        ul.style.transform = 'translateX(' + translatex + 'px)';
        flag = true; // If the user's finger moves, we will judge again, otherwise we will not judge the effect
        e.preventDefault(); // Prevent scrolling
    });
    // When the finger leaves, judge whether to rebound or play the previous one or the next one according to the moving distance
    ul.addEventListener('touchend', function (e) {
        if (flag) {
            // (1) If the moving distance is greater than 50 pixels, we will play the previous or next one
            if (Math.abs(moveX) > 50) {
                // If it is right sliding, it means that the previous moveX is positive
                if (moveX > 0) {
                    index--;
                } else {
                    // If it's left sliding, it's playing the next one. moveX is negative
                    index++;
                }
                var translatex = -index * w;
                ul.style.transition = 'all .3s';
                ul.style.transform = 'translateX(' + translatex + 'px)';
            } else {
                // (2) If the moving distance is less than 50 pixels, we will rebound
                var translatex = -index * w;
                ul.style.transition = 'all .1s';
                ul.style.transform = 'translateX(' + translatex + 'px)';
            }
        }
        // Restart the timer when your fingers leave
        clearInterval(timer);
        timer = setInterval(function () {
            index++;
            var translatex = -index * w;
            ul.style.transition = 'all .3s';
            ul.style.transform = 'translateX(' + translatex + 'px)';
        }, 2000);
    });


    // Return to top module fabrication
    var goBack = document.querySelector('.goBack');
    var nav = document.querySelector('nav');
    window.addEventListener('scroll', function () {
        if (window.pageYOffset >= nav.offsetTop) {
            goBack.style.display = 'block';
        } else {
            goBack.style.display = 'none';
        }
    });
    goBack.addEventListener('click', function () {
        window.scroll(0, 0);
    })
})

2. click delay solution

The click event on the mobile terminal will have a delay of 300ms because double tap to zoom the page will be caused by double clicking on the mobile terminal screen. Solution:

1. Disable scaling. The browser disables the default double-click zoom behavior and removes the 300ms click delay.

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

The principle is:

  1. When we touch the screen with our fingers, record the current touch time
  2. When our fingers leave the screen, we subtract the time we touch from the time we leave
  3. If the time is less than 150ms and the screen has not been swiped, we define it as clicking

The click event on the mobile terminal will have a delay of 300ms because double tap to zoom the page will be caused by double clicking on the mobile terminal screen. Solution:

3. Use plug-ins. The fastclick plug-in solves the 300ms delay.  

3. Common development plug-ins of mobile terminal

1. What is a plug-in

The mobile terminal requires rapid development, so we often use some plug-ins to help me complete the operation. So what is a plug-in?  

js plug-in is a js file, which is written according to certain specifications, which is convenient for the program to show the effect, has specific functions and is easy to call. Such as rotation chart and waterfall flow plug-in.

Features: it generally exists specially to solve a certain problem. Its function is single and relatively small.

We used to write animate JS is also the simplest plug-in

The fastclick plug-in solves the 300ms delay.

Use the delay GitHub official website address: https://github.com/ftlabs/fastclick  

2. Use of plug-ins

  1. Import js plug-in file.
  2. Use according to the specified syntax.  

The fastclick plug-in solves the 300ms delay.

Use the delay GitHub official website address: https://github.com/ftlabs/fastclick  

 3. Use of swiper plug-in

Chinese official website address: https://www.swiper.com.cn/   

  1. Import plug-in related files.
  2. Use according to the specified syntax

4. Common plug-ins of other mobile terminals

  • superslide: http://www.superslide2.com/  
  • iscroll: https://github.com/cubiq/iscroll 

5. Usage Summary of plug-ins

  1. Confirm the functions implemented by the plug-in
  2. Go to the official website to check the instructions
  3. Download plug-ins
  4. Open the demo instance file, view the relevant files to be imported, and import
  5. Copy the structure html, style css and js code in the demo instance file

6. Exercise - Mobile Video plug-in ZY media. js

H5 provides us with a video tag, but the support of the browser is different.

We can solve different video format files through source.

However, we can only write our own code to solve the appearance style, pause, play, full screen and other functions.

At this time, we can use the plug-in method to make.  

4. Common development framework of mobile terminal

1. Framework overview

Framework, as its name implies, is a set of architecture. It will provide users with a relatively complete solution based on its own characteristics. The control of the framework lies in the framework itself, and users should develop according to some specifications specified in the framework

Plug-ins generally exist specifically to solve a problem. Their functions are single and relatively small.  

The commonly used front-end frameworks include Bootstrap, Vue, Angular, React, etc. It can develop both PC and mobile terminals. The commonly used mobile terminal plug-ins include swiper, superslide, iscoll, etc.  

Framework: large and comprehensive, a complete set of Solutions

Plug in: a small and specific solution for a certain function

2. Bootstrap

Bootstrap is a concise, intuitive and powerful front-end development framework, which makes web development faster and simpler.

It can develop both PC and mobile terminals

Steps for using Bootstrap JS plug-in:

  1. Import relevant js files
  2. Copy HTML structure
  3. Modify the corresponding style
  4. Modify corresponding JS parameters

3, Local storage

1. Local storage

With the rapid development of the Internet, web-based applications become more and more common, but also become more and more complex. In order to meet a variety of needs, a large amount of data will be stored locally. HTML5 specification puts forward relevant solutions.  

Local storage characteristics

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

2. window.sessionStorage

  1. The lifecycle is to close the browser window
  2. Data can be shared in the same window (page)
  3. Stored and used in the form of key value pairs

Store data:

 

Get data:

 

Delete data:

 

Delete all data:

 

<body>
    <input type="text">
    <button class="set">Store data</button>
    <button class="get">get data</button>
    <button class="remove">Delete data</button>
    <button class="del">Clear all data</button>
    <script>
        console.log(localStorage.getItem('username'));  // Here is the window to print another page Content stored by localstorage

        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 values 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 values 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>

3. window.localStorage

  1. The declaration cycle takes effect permanently, and the closed page will also exist unless manually deleted
  2. Multiple windows (pages) can be shared (the same browser can be shared)
  3. Stored and used in the form of key value pairs

Store data:

 

Get data:

Delete data:

Delete all data:

Case: remember user name

If you check remember user name, the last login user name will be automatically displayed in the text box the next time the user opens the browser

  1. Save the data and use it for local storage
  2. The user name can also be displayed when the page is closed, so localStorage is used
  3. Open the page and first judge whether there is this user name. If so, display the user name in the form and check the check box
  4. The change event occurs when the check box changes
  5. If checked, it will be stored, otherwise it will be removed
<body>
    <input type="text" id="username"> <input type="checkbox" name="" id="remember"> Remember user name
    <script>
        var username = document.querySelector('#username');
        var remember = document.querySelector('#remember');
        if (localStorage.getItem('username')) {     // If the local localStorage stores the value of username
            username.value = localStorage.getItem('username');   // Then put the value in the text box
            remember.checked = true;       //Check the box
        }
        remember.addEventListener('change', function() {   // Create a checkbox change event
            if (this.checked) {     //If checked
                localStorage.setItem('username', username.value)  // Then the value is stored
            } else {
                localStorage.removeItem('username');   // Otherwise, remove the value
            }
        })
    </script>
</body>

 

Topics: Javascript html css