Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Example Analysis of JavaScript Animation function Encapsulation

2025-02-24 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

Editor to share with you the example analysis of JavaScript animation function encapsulation. I hope you will get something after reading this article. Let's discuss it together.

First, the principle of animation function

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

Implementation steps:

Get the current location of the box

Let the box add 1 moving distance to its current position

Use a timer to repeat this operation over and over again.

Add a condition to end the timer

Note that this element needs to add positioning before you can use element.style.left

As follows:

Given a box, let it slowly move to the location of the 300px.

The code is as follows:

Div {position: absolute; left: 0; top: 0; width: 100px; height: 100px; background-color: cyan;} var div = document.querySelector ('div'); var timer = setInterval (function () {if (div.offsetLeft > = 300) {clearInterval (timer) } div.style.left = div.offsetLeft + 1 + 'px';}, 30)

The running result is:

It runs successfully.

But what if there are several elements that need to be animated at the same time? We can consider encapsulating it into a simple animation function.

2. Simple encapsulation of animation function

The function needs to pass two parameters, the animated object and the distance to which it is moved. As follows:

Function animate (obj,target) {var timer = setInterval (function () {if (obj.offsetLeft > = target) {clearInterval (timer);} obj.style.left = obj.offsetLeft + 1 + 'px';}, 30);}

We can achieve the animation effect by calling the function encapsulated above. For example, given two different boxes, call the animation function:

.box1 {position: absolute; left: 0; top: 50px; width: 100px; height: 100px; background-color: cyan;} .box2 {position: absolute; left: 0; top: 155px; width: 150px; height: 150px Background-color: deepskyblue;} function animate (obj,target) {var timer = setInterval (function () {if (obj.offsetLeft > = target) {clearInterval (timer);} obj.style.left = obj.offsetLeft + 1 + 'px';}, 30) } var box1 = document.querySelector ('.box1'); var box2 = document.querySelector ('.box2'); animate (box1300); animate (box2400)

The effect is:

The effect of animation has been realized successfully.

But the animation function encapsulated above is still problematic. Every time we call an animation function, it will open up a piece of memory space for us, which will cause a waste of memory resources. And the animation function we call each time is named with the same name, which is easy to cause ambiguity, so we can use different timers for different elements (we use our own timers).

Third, the animation function records different timers for different elements

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

By adding timers to different elements by adding attributes to the object, we can encapsulate it as follows:

Function animate (obj,target) {obj.timer = setInterval (function () {if (obj.offsetLeft > = target) {clearInterval (obj.timer);} obj.style.left = obj.offsetLeft + 1 + 'px';}, 30);}

Of course, if we want to animate an element after we have done a series of operations, we can add a specific event to it and write the function call in the event

Take the first example as an example, add a click event to it, and then move the box when the button is clicked:

Var box1 = document.querySelector ('.box1'); var btn = document.querySelector ('button') btn.addEventListener (' click',function () {animate (box1300);})

The effect is:

The effect is achieved, but what happens if we keep clicking the button?

We will find that when we keep clicking the button, the box runs faster and faster because we start too many timers at the same time. How to solve the problem? The solution is to let our element first clear the previous timer, leaving only one timer to execute, so we can add a clear timer operation at the top of the function. The code is:

Function animate (obj,target) {clearInterval (obj.timer); obj.timer = setInterval (function () {if (obj.offsetLeft > = target) {clearInterval (obj.timer);} obj.style.left = obj.offsetLeft + 1 + 'px';}, 30);} var box1 = document.querySelector (' .box1') Var btn = document.querySelector ('button'); btn.addEventListener (' click',function () {animate (box1300);})

The running effect at this time is

It was successfully realized.

Through the above series of operations, we can find that the animation we achieve is uniform, in order to make the effect more beautiful, we can make our animation run at a slow speed.

Fourth, the principle of retarding effect

Slow animation is to change the speed of an element, and the most common thing is to slow down the speed.

Idea: let the box slowly reduce the distance each time it moves, and the speed will slowly fall.

Core algorithm: (target value-current position) / 10 as the distance step for each move

Condition for stopping: stop the timer when the current box position is equal to the target position

Note that the step size value needs to be rounded.

In the above example, when we click the button and let the element move at a slow speed, we can change the encapsulated animation function to:

Function animate (obj,target) {clearInterval (obj.timer) obj.timer = setInterval (function () {var step = (target-obj.offsetLeft) / 10; if (obj.offsetLeft = = target) {clearInterval (obj.timer);} obj.style.left = obj.offsetLeft + step + 'px';}, 30);}

The results are as follows:

Doesn't this effect look better? But let's check how far our element has moved and whether it is just at the position of the target value 300px.

Through inspection, we found that our element did not reach the specified position, because there is something wrong with our step size formula, and there may be decimals during division, resulting in a deviation in position. so we need to round up the step size formula, because the element is moving forward (positive direction), so our strategy is to round up:

Var step = Math.ceil ((target-obj.offsetLeft) / 10)

At this point, let's take a look at the final target location:

At this point, we just reached the target position.

Fifth, the animation function moves between multiple target values

But what if our step size is negative?

For example, you now have a box and add two buttons to it, one to move the element to the location of 400px and one to move the element to 700px:

Function animate (obj,target) {clearInterval (obj.timer) obj.timer = setInterval (function () {var step = Math.ceil ((target-obj.offsetLeft) / 10); if (obj.offsetLeft > = target) {clearInterval (obj.timer);} obj.style.left = obj.offsetLeft + step + 'px';}, 30);} var box1 = document.querySelector (' .box1') Var btn = document.querySelectorAll ('button') btn [0] .addEventListener (' click',function () {animate (box1400);}) btn [1] .addEventListener ('click',function () {animate (box1700);})

The results are as follows:

At this time, it is found that when we move forward, the element can accurately reach the target position, and the element can also achieve the effect of moving between two pixels, but the position reached when moving backward is not the target position. this is because our element is in reverse motion, and then we should also round the step to the position of the reverse length, that is, rounding down.

At this time, we should judge the step size condition. If the step size is greater than zero, it will be rounded up, and if the step size is less than zero, it will be rounded down. The adjusted step size formula is:

Var step = (target-obj.offsetLeft) / 10; step > 0? Math.ceil (step): Math.floor (step)

Let's take a look at the effect at this time:

The problem is solved.

But at this point, we simply implement the movement of an element in two positions. What if we want to change the color after it moves? We can do this by adding a callback function to the animation function.

6. Add callback function to animation function

Callback function principle: a function can be used as an argument. Pass this function as an argument to another function, and then execute the passed function after that function is executed. this process is called a callback.

The position written by the callback function: the position where the timer ends.

The specific implementation code is as follows:

Function animate (obj,target,callback) {clearInterval (obj.timer) obj.timer = setInterval (function () {var step = (target-obj.offsetLeft) / 10; step = step > 0? Math.ceil (step): Math.floor (step); if (obj.offsetLeft = = target) {clearInterval (obj.timer); if (callback) {callback ();}} obj.style.left = obj.offsetLeft + step + 'px';}, 30) } var box1 = document.querySelector ('.box1'); var btn = document.querySelectorAll ('button'); btn [0] .addEventListener (' click',function () {animate (box1,400,function () {box1.style.backgroundColor = 'pink';})) }) btn [1] .addEventListener ('click',function () {animate (box1,700,function () {box1.style.backgroundColor =' red';});})

The results are as follows:

After reading this article, I believe you have some understanding of "sample Analysis encapsulated by JavaScript Animation function". If you want to know more about it, you are welcome to follow the industry information channel. Thank you for reading!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report