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

Usage of the target attribute of the html tag a

1: If you use the tag <a> to link to a page,...

A QQ chat room based on vue.js

Table of contents Introduction The following is a...

Steps and pitfalls of upgrading linux mysql5.5 to mysql5.7

Table of contents Linux MySQL 5.5 upgraded to MyS...

Double loading issue when the page contains img src

<br />When the page contains <img src=&qu...

Solution to prevent caching in pages

Solution: Add the following code in <head>: ...

Best way to replace the key in json object

JSON (JavaScript Object Notation, JS Object Notat...

React + Threejs + Swiper complete code to achieve panoramic effect

Let’s take a look at the panoramic view effect: D...

Detailed explanation of the solution for migrating antd+react projects to vite

Antd+react+webpack is often the standard combinat...

Vue uses plug-ins to cut pictures in proportion

This article shares the specific code of Vue usin...

Element-ui's built-in two remote search (fuzzy query) usage explanation

Problem Description There is a type of query call...

VSCode configuration Git method steps

Git is integrated in vscode, and many operations ...

An article teaches you how to use js to achieve the barrage effect

Table of contents Create a new html file: Create ...

Mini Program to Implement Calculator Function

This article example shares the specific code of ...

Using Docker Enterprise Edition to build your own private registry server

Docker is really cool, especially because it'...