JavaScript to achieve elastic navigation effect

JavaScript to achieve elastic navigation effect

This article shares the specific code for JavaScript to achieve elastic navigation effects for your reference. The specific content is as follows

Mainly using offsetX

1. Build the scaffolding first:

* {
      margin: 0;
      padding: 0;
        }
        
        .nav {
            width: 900px;
            height: 63px;
            background: url(images/doubleOne.png) no-repeat right center;
            border: 1px solid #ccc;
            margin: 100px auto;
            position: relative;
        }
        
        ul {
            position: relative;
            z-index: 999;
        }
        
        ul>li {
            list-style: none;
            float: left;
            width: 88px;
            height: 63px;
            line-height: 63px;
            text-align: center;
        }
        
        span {
            display: inline-block;
            width: 88px;
            height: 63px;
            background: url("images/tMall.png") no-repeat;
            position: absolute;
            left: 0;
            top: 0;
}
<div class="nav">
        <ul>
            <li>Double 11 Carnival</li>
            <li>Clothing venue</li>
            <li>Digital home appliances</li>
            <li>Home building materials</li>
            <li>Mother and baby clothing</li>
            <li>Mobile venue</li>
            <li>Beauty and makeup venue</li>
            <li>Import Venue</li>
            <li>Fliggy Travel</li>
        </ul>
        <span></span>
</div> 

2. Write the logic part

//1. Get the element to be operated const oItems = document.querySelectorAll("li");
 let oSpan = document.querySelector("span");
 
//2. Listen for click events of each menu for (let i = 0; i < oItems.length; i++) {
            let item = oItems[i];
            item.onclick = function() {
                //offsetLeft gets the offset of the clicked element from the first positioned ancestor element // console.log(this.offsetLeft);
                // oSpan.style.left = this.offsetLeft + 'px';
                //Call function easeAnimation(oSpan, {
                    "left": this.offsetLeft
                });
            };
        }

animation.js

(function() {
    /**
     * Uniform speed animation* @param {*} ele Element to perform animation* @param {*} obj Which attributes of the element need to be animated* @param {*} fn Operations that may need to be performed after the animation is completed* 
     * Calling method reference* linearAnimation(oDiv, {
                "marginTop": 500,
                "marginLeft": 300
        });
     */
    function linearAnimation(ele, obj, fn) {
        clearInterval(ele.timerId);
        ele.timerId = setInterval(function() {
            //The flag variable is used to mark whether all properties have completed the animation. let flag = true;
 
            for (let key in obj) {
                let target = obj[key];
 
                // 1. Get the current position of the element // let begin = parseInt(ele.style.width) || 0;
                let style = getComputedStyle(ele);
                // let begin = parseInt(style.width) || 0;
                let begin = parseFloat(style[key]) || 0;
 
                // 2. Define variables to record step length let step = (begin - target) > 0 ? -13 : 13;
 
                // 3. Calculate the new position begin += step;
                // console.log(Math.abs(target - begin), Math.abs(step));
                if (Math.abs(target - begin) > Math.abs(step)) { //Animation not completed flag = false;
                } else { //After executing the animation begin = target;
                }
 
                // 4. Reset the element's position // ele.style.width = begin + "px";
                ele.style[key] = begin + "px";
            }
 
            //Judge whether the animation has been executed if (flag) {
                //After the animation is finished, turn off the timer clearInterval(ele.timerId);
 
                //Judge whether the fn function is passed in, execute it if it is passed in, otherwise do not execute it // if (fn) {
                // fn();
                // }
                fn && fn();
            }
        }, 100);
    }
 
    //Easy animation function easeAnimation(ele, obj, fn) {
        clearInterval(ele.timerId);
        ele.timerId = setInterval(function() {
            //The flag variable is used to mark whether all properties have completed the animation. let flag = true;
 
            for (let key in obj) {
                let target = obj[key];
 
                // 1. Get the current position of the element let style = getComputedStyle(ele);
                let begin = parseInt(style[key]) || 0;
 
                // 2. Define variable record step size // Formula: (end position - start position) * easing coefficient (0 ~ 1)
                let step = (target - begin) * 0.3;
 
                // 3. Calculate the new position begin += step;
                if (Math.abs(Math.floor(step)) > 1) {
                    flag = false;
                } else {
                    begin = target;
                }
                // 4. Reset the element's position ele.style[key] = begin + "px";
            }
 
            //Judge whether the animation has been executed if (flag) {
                //After the animation is finished, turn off the timer clearInterval(ele.timerId);
 
                //Judge whether the fn function is passed in, and execute it if it is, otherwise do not execute fn && fn();
            }
        }, 100);
    }
 
    // Bind the function to the window object so that it can be used globally window.linearAnimation = linearAnimation;
    window.easeAnimation = easeAnimation;
})(); 

The above is the full content of this article. I hope it will be helpful for everyone’s study. I also hope that everyone will support 123WORDPRESS.COM.

You may also be interested in:
  • Pure JS to achieve elastic navigation bar effect

<<:  How to keep the content within the container when the flex layout is stretched by child elements

>>:  9 Tips for Web Page Layout

Recommend

12 Laws of Web Design for Clean Code [Graphic]

Beautiful code is the foundation of a beautiful we...

How to deploy Vue project using Docker image + nginx

1. Packaging Vue project Enter the following name...

HTML Basics - Simple Example of Setting Hyperlink Style

*** Example of setting the style of a hyperlink a...

Method of iframe adaptation in web responsive layout

Problem <br />In responsive layout, we shou...

Double loading issue when the page contains img src

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

MySQL triggers: creating and using triggers

This article uses examples to describe the creati...

How to simulate enumeration with JS

Preface In current JavaScript, there is no concep...

Detailed explanation of MySQL cursor concepts and usage

This article uses examples to explain the concept...

Implementing Priority Queue in JavaScript

Table of contents 1. Introduction to priority que...

Virtual Box tutorial diagram of duplicating virtual machines

After getting used to VM, switching to BOX is a l...

mysql8 Common Table Expression CTE usage example analysis

This article uses an example to describe how to u...

Key features of InnoDB - insert cache, write twice, adaptive hash index details

The key features of the InnoDB storage engine inc...

Summary of the differences between global objects in nodejs and browsers

In Node.js, a .js file is a complete scope (modul...

Linux installation MongoDB startup and common problem solving

MongoDB installation process and problem records ...

Vue.js implements simple folding panel

This article example shares the specific code of ...