JavaScript explains the encapsulation and use of slow-motion animation

JavaScript explains the encapsulation and use of slow-motion animation

Implementing process analysis

(1) How to call repeatedly?

Answer: Encapsulate a function and call it once

Code Analysis:

function animate(obj, target, callback) { //Detailed implementation steps};

animate: (animation function)

obj (animation object): to whom the animation effect is added

target (target value): how far to move to

callback (callback function): what function to execute at the same time

(2) How to achieve the easing effect? (Easy-motion animation core algorithm)

Answer: Moving distance = (target value - current box position) / 10. The moving distance will gradually decrease until it stops, thus realizing the easing principle.

Code Analysis:

var step = (target - obj.offsetLeft) / 10;

step (moving distance): the distance the element is to move

target (target value): how far to move to

obj.offsetLeft (the current position of the box): the current distance of the box from the left side

(3) Why can’t it move to the specified position? (The target distance given is 500px, and it stops at 496.4)

Answer: Because it needs to be rounded, positive numbers are rounded up and negative numbers are rounded down

Code Analysis:

step = step > 0 ? Math.ceil(step) : Math.floor(step);

If the distance setp is to move is a positive number, it is rounded up, if it is a negative number, it is rounded down, and a ternary expression is used to optimize the code and improve the overall quality.

(4) How to make the target element actually move?

A: Add a timer and assign the real-time moving distance (step length) to the element

Code Analysis:

 var timer = setInterval(function () { //Detailed implementation code}, 15); //Add timer obj.style.left = obj.offsetLeft + step + 'px'; //Step length

1. Add a name to the timer to make it easier to clear the timer. Set the time to 15 (15 is often used in actual development)

2. The value on the left side of the element = the distance from the element to the left + the moving distance + 'px' (remember to add the px unit). The implementation principle is to continuously assign the latest value to the element to achieve the effect of animation.

(5) Why does it become so annoying or faster and faster?

Answer: Because the timer is added repeatedly, the timer needs to be cleared each time it is called

Code Analysis:

clearInterval(timer);

There are two places that need to be cleared. The first is when the easing animation function is just called to avoid ghosts and speed breaks. The second is to determine whether the element has reached the specified position. If it has reached the specified position, stop the timer.

Case test:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .sliderbar {
            /* width: 240px; */
            /* height: 40px; */
            /* Parent box positioning is based on actual requirements*/
            position: absolute;
            right: 0;
            top: 100px;
            text-align: center;
            line-height: 40px;
            /* display: block; */
            width: 40px;
            height: 40px;
            cursor: pointer;
        }
        .sp {
            position: relative;
            color: #fff;
        }
        
        .con {
            /* Set absolute positioning so it floats in the parent box*/
            position: absolute;
            left: 0;
            top: 0;
            width: 200px;
            height: 40px;
            background-color: pink;
            z-index: -1;
            color: #fff;
        }
    </style>
    <script src="./animate.js"></script>
</head>
 
<body>
    <div class="sliderbar">
        <span class="sp">←</span>
        <div class="con">Problem feedback</div>
    </div>
 
    <script>
        var sliderbar = document.querySelector('.sliderbar');
        // var sp = document.querySelector('.sp');
        var con = document.querySelector('.con');
        sliderbar.addEventListener('mouseenter', function() {
            //animate(obj, target, callback);
            animate(con, -160, function() {
                sliderbar.children[0].innerHTML = '→';
            });
        })
        sliderbar.addEventListener('mouseleave', function() {
            //animate(obj, target, callback);
            animate(con, 0, function() {
                sliderbar.children[0].innerHTML = '←';
 
            });
        })
    </script>
</body>
</html>

The overall idea is to call the animation function by adding mouse events to the box to achieve the final effect.

Operation effect:

The final encapsulation code of the easing animation function (animate.js):

function animate(obj, target, callback) {

//Call the function to clear the timer once to avoid problems

clearInterval(obj.timer)

//Add timer

obj.timer = setInterval(function () {

//The step value is written into the timer and changed to an integer (round up)

var step = (target - obj.offsetLeft) / 10;

//Integers are taken from the larger end, negative numbers are taken from the smaller end

step = step > 0 ? Math.ceil(step) : Math.floor(step);

if (obj.offsetLeft == target) {

// If the specified position has been reached, stop the timer

clearInterval(obj.timer);

//The callback function is written after the timer ends

callback && callback();

}

//Change the value of each step to a gradually smaller value

obj.style.left = obj.offsetLeft + step + 'px';

}, 15);

}

Life never stops, learning never stops, keyboards are worn out, and monthly salary exceeds ten thousand! Come on, coder

This is the end of this article about the encapsulation and use of JavaScript slow-motion animation. For more relevant JavaScript slow-motion animation content, please search for previous articles on 123WORDPRESS.COM or continue to browse the related articles below. I hope everyone will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JavaScript to achieve slow motion animation effect
  • JavaScript implements left and right slow animation function
  • Encapsulation method of JavaScript slow motion animation function
  • js to achieve slow motion animation
  • JavaScript to achieve slow motion animation
  • Tween.js easing tween animation algorithm example
  • js realizes the navigation bar effect with slow animation

<<:  Analysis of the principle of Nginx using Lua module to implement WAF

>>:  Set the default text of the search box. The default text disappears when the mouse is clicked.

Recommend

A brief discussion on the types of node.js middleware

Table of contents Overview 1. Application-level m...

A detailed introduction to Linux system configuration (service control)

Table of contents Preface 1. System Service Contr...

Super detailed tutorial to implement Vue bottom navigation bar TabBar

Table of contents Project Introduction: Project D...

Sliding menu implemented with CSS3

Result:Implementation code: <!DOCTYPE html>...

vue.config.js packaging optimization configuration

The information on Baidu is so diverse that it...

Vue3 AST parser-source code analysis

Table of contents 1. Generate AST abstract syntax...

React implementation example using Amap (react-amap)

The PC version of React was refactored to use Ama...

Mysql accidental deletion of data solution and kill statement principle

mysql accidentally deleted data Using the delete ...

Modify the boot time of grub in ubuntu

The online search to modify the grub startup time...

Briefly describe the use and description of MySQL primary key and foreign key

Table of contents 1. Foreign key constraints What...

CSS to achieve fast and cool shaking animation effect

1. Introduction to Animate.css Animate.css is a r...

Mysql string interception and obtaining data in the specified string

Preface: I encountered a requirement to extract s...