This article mainly introduces the method of JS to realize multi-object movement. It analyzes the principles and related operation techniques of JavaScript to realize multi-object movement in detail in the form of examples. Friends in need can refer to this article
The example analyzes the method of realizing multi-object movement in JS. Share it with everyone for your reference, the details are as follows:
Basic steps
1. Get the elements for multi-object movement through getElementsByTagName
2. Then the for loop traverses the elements and adds events
3. Define the startMove function, which requires two parameters, the current "doing exercise" element, and the target value target
Note: In multi-object motion, everything cannot be shared;
<script> window.onload = function(){ var liTags = document.getElementsByTagName('li'); // 第一步 for(var i=0;i<liTags.length;i++){ // 第二步 liTags[i].onmouseover = function () { startMove(this,400); } liTags[i].onmouseout = function () { startMove(this,200); } } } var timer = null; function startMove(obj,iTarget) { // 第三步,2个参数 clearInterval(timer); timer = setInterval(function () { var iSpeed = (iTarget - obj.offsetWidth)/10; iSpeed = iSpeed>0 ?Math.ceil(iSpeed):Math.floor(iSpeed);// 缓冲运动注意取整处理 if(obj.offsetWidth == iTarget){ clearInterval(timer); }else{ obj.style.width = obj.offsetWidth+iSpeed+'px'; } },30); } </script>
Problem:
When the moving in and out speed is relatively fast , it will appear that some li cannot return to its original state and is stuck in the middle; This is because all li share a timer;
When the mouse moves into the first When a li is reached, call startMove to start a timer; when the mouse removes the li, a timer also needs to be started to return the li to its original position. When the li reaches halfway, we move into the second li, and the timer will be cleared first. At this time, the first li got stuck halfway.
Solve this problem: Let each li have its own timer to control their changes, and define it for each li during the for loop One of your own timer
liTags[i].timer = null;// 给每个li都添加一个timer
Then the timer used every time in starMove is the current li's own, so there will be no interference with each other.
The previous timer here has been changed to obj.timer
(the current object’s own timer); there is no problem here.
The complete code is as follows:
<body> <ul> <li></li> <li></li> <li></li> <li></li> </ul> </body>
Add dot style:
<style> ul{list-style: none;} ul li{ margin: 10px; width: 200px;height: 50px; background: lightblue; } </style>
Complete js code
<script> window.onload = function(){ var liTags = document.getElementsByTagName('li'); for(var i=0;i<liTags.length;i++){ liTags[i].timer = null;// 给每个li都添加一个timer liTags[i].onmouseover = function () { startMove(this,400); } liTags[i].onmouseout = function () { startMove(this,200); } } } function startMove(obj,iTarget) { clearInterval(obj.timer); obj.timer = setInterval(function () { var iSpeed = (iTarget - obj.offsetWidth)/10; iSpeed = iSpeed>0 ?Math.ceil(iSpeed):Math.floor(iSpeed); if(obj.offsetWidth == iTarget){ clearInterval(obj.timer); }else{ obj.style.width = obj.offsetWidth+iSpeed+'px'; } },30); } </script>
Then look at an example: multi-object movement-changing transparency
<script> window.onload = function () { var aImgs = document.getElementsByTagName('img'); for(var i=0;i<aImgs.length;i++){ aImgs[i].timer = null; aImgs[i].alpha = 100; // 把公用的alpha改成每个img对象都有的属性 aImgs[i].onmouseover = function () { startMove(this,30); } aImgs[i].onmouseout = function () { startMove(this,100); } } } // var alpha = 100; 这里alpha在多物体运动里 不能公用 function startMove(obj,iTarget) { clearInterval(obj.timer); var iSpeed = (iTarget - obj.alpha)/10; iSpeed = iSpeed>0 ? Math.ceil(iSpeed): Math.floor(iSpeed); obj.timer = setInterval(function(){ if(obj.alpha == iTarget){ clearInterval(obj.timer); }else{ obj.alpha += iSpeed; obj.style.opacity =obj.alpha/100; obj.style.filter = 'alpha(opacity:'+obj.alpha+')'; } },30); } </script>
The above is what I compiled for everyone. I hope it will be helpful to everyone in the future.
Related articles:
What are the methods to add new properties of objects to the detection sequence in vue?
How to achieve the animation effect of bouncing off the edge in jQuery?
How to use sass in vue cli webpack (detailed tutorial)
How to change the P tag text value in jQuery
By creating tags in js dynamics and setting attribute methods (detailed tutorial)
Implement the method of adding and assigning tag sub-elements in jQuery
How to implement the commonly used message box in JS?
The above is the detailed content of How to implement multi-object movement in JS (detailed tutorial). For more information, please follow other related articles on the PHP Chinese website!

Understanding how JavaScript engine works internally is important to developers because it helps write more efficient code and understand performance bottlenecks and optimization strategies. 1) The engine's workflow includes three stages: parsing, compiling and execution; 2) During the execution process, the engine will perform dynamic optimization, such as inline cache and hidden classes; 3) Best practices include avoiding global variables, optimizing loops, using const and lets, and avoiding excessive use of closures.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

Python and JavaScript have their own advantages and disadvantages in terms of community, libraries and resources. 1) The Python community is friendly and suitable for beginners, but the front-end development resources are not as rich as JavaScript. 2) Python is powerful in data science and machine learning libraries, while JavaScript is better in front-end development libraries and frameworks. 3) Both have rich learning resources, but Python is suitable for starting with official documents, while JavaScript is better with MDNWebDocs. The choice should be based on project needs and personal interests.

The shift from C/C to JavaScript requires adapting to dynamic typing, garbage collection and asynchronous programming. 1) C/C is a statically typed language that requires manual memory management, while JavaScript is dynamically typed and garbage collection is automatically processed. 2) C/C needs to be compiled into machine code, while JavaScript is an interpreted language. 3) JavaScript introduces concepts such as closures, prototype chains and Promise, which enhances flexibility and asynchronous programming capabilities.

Different JavaScript engines have different effects when parsing and executing JavaScript code, because the implementation principles and optimization strategies of each engine differ. 1. Lexical analysis: convert source code into lexical unit. 2. Grammar analysis: Generate an abstract syntax tree. 3. Optimization and compilation: Generate machine code through the JIT compiler. 4. Execute: Run the machine code. V8 engine optimizes through instant compilation and hidden class, SpiderMonkey uses a type inference system, resulting in different performance performance on the same code.

JavaScript's applications in the real world include server-side programming, mobile application development and Internet of Things control: 1. Server-side programming is realized through Node.js, suitable for high concurrent request processing. 2. Mobile application development is carried out through ReactNative and supports cross-platform deployment. 3. Used for IoT device control through Johnny-Five library, suitable for hardware interaction.

I built a functional multi-tenant SaaS application (an EdTech app) with your everyday tech tool and you can do the same. First, what’s a multi-tenant SaaS application? Multi-tenant SaaS applications let you serve multiple customers from a sing

This article demonstrates frontend integration with a backend secured by Permit, building a functional EdTech SaaS application using Next.js. The frontend fetches user permissions to control UI visibility and ensures API requests adhere to role-base


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Zend Studio 13.0.1
Powerful PHP integrated development environment

SublimeText3 English version
Recommended: Win version, supports code prompts!

Dreamweaver CS6
Visual web development tools

MantisBT
Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft