Reference and packaging of JavaScript animation functions for front-end learning

Posted by taith on Mon, 14 Feb 2022 12:57:50 +0100

Animation function encapsulation

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

Animation functions record 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.

 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
            obj.timer = setInterval(function() {
                if (obj.offsetLeft >= target) {
                    // The essence of stopping animation is to stop the timer
       = obj.offsetLeft + 1 + 'px';

            }, 30);

Animation function encapsulation

Principle of slow motion animation effect

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


  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

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

Add callback function to dynamic 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.

Animation full version code:

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
    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 stopping animation is to stop the 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.offsetLeft + step + 'px';

    }, 15);

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 execution of the animation using the callback function, flag = true, turn on the faucet

Case: back to top

  1. Return to top with animation
  2. At this point, we can continue to use our encapsulated animation functions
  3. Just change all the left related values to be related to the vertical scrolling distance of the page
  4. How much page scrolls can be through window Pageyoffset
  5. Finally, page scrolling, using window scroll(x,y)
  //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) {
           = 'fixed';
           = sliderbarTop + 'px';
                } else {
           = 'absolute';
           = '300px';
                // 4. When our page scrolls to the main box, the goback module is displayed
                if (window.pageYOffset >= mainTop) {
           = 'block';
                } else {
           = '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 window objects are scrolling windows
            animate(window, 0);

Case: tendon head cloud case

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

Touch Event

Touch screen event overview

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:

[the external chain image transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the image and upload it directly (img-oT0zQoRJ-1644837044313)(images \ image 1.png)]

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:

[the external chain picture transfer fails. The source station may have an anti-theft chain mechanism. It is recommended to save the picture and upload it directly (img-WRLEogF6-1644837044316)(images \ picture 2.png)]

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

Case: dragging elements at the moving end

  1. touchstart, touchmove and touchend can drag elements

  2. However, dragging elements 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 your fingers move

  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();

    This time, we introduced the encapsulation and use of animation functions. Next time, we will introduce the native js writing method of rotation map, including the mobile terminal.

Topics: Javascript Front-end