This time I will bring you an in-depth JS movement in JavaScript. JS movement using JavaScriptWhat are the precautions?The following is a practical case, let’s take a look.
JS Movement Basics
Motion Framework
When starting movement, close the existing timer
Separate movement and stop (if/else)
1. Uniform motion
nbsp;HTML> <meta> <title>01-运动基础</title> <style> #div1 {width:200px; height:200px; background:red; position:absolute; top:50px; left:0px;} </style> <script> //定时器 var timer=null; function startMove() { var oDiv=document.getElementById('div1'); //为了保证只有一个定时器工作,把之前的定时器全关了 clearInterval(timer); timer=setInterval(function (){ var speed=1; if(oDiv.offsetLeft>=300) { clearInterval(timer); } else { oDiv.style.left=oDiv.offsetLeft+speed+'px'; } }, 30); } </script><input><div></div>
<!DOCTYPE HTML><html><head><meta charset="utf-8"><title>无标题文档</title><style>#div1 {width:150px; height:200px; background:green; position:absolute; left:-150px;}#div1 span {position:absolute; width:20px; height:60px; line-height:20px; background:blue; right:-20px; top:70px;}</style><script>window.onload=function (){ var oDiv=document.getElementById('div1'); oDiv.onmouseover=function () { startMove(0); }; oDiv.onmouseout=function () { startMove(-150); }; };var timer=null;function startMove(iTarget){ var oDiv=document.getElementById('div1'); clearInterval(timer); timer=setInterval(function (){ //先初始化速度 var speed=0; //开始位置 > 终点位置:比方 起点:350 终点 50 要想到50这个位置,速度得为:-10; //oDiv.offsetLeft : 起点位置 //iTarget终点位置 if(oDiv.offsetLeft>iTarget) { speed=-10; } else { speed=10; } //这个函数存在一个漏洞,如果oDiv.offsetLef 刚好t >=iTarget 定时器不会停止 if(oDiv.offsetLeft==iTarget) { clearInterval(timer); } else { oDiv.style.left=oDiv.offsetLeft+speed+'px'; } }, 30); }</script></head><body><div id="div1"> <span>分享到</span></div></body></html>
3.Fade in and out
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <title>03-淡入淡出</title> <style> div{ width: 200px; height: 200px; background-color: red; opacity:0.3; //兼容chrome和ff filtr:alpha(opacity:30);//兼容低版本的IE } </style> <script> window.onload = function () { var oDiv = document.getElementsByTagName('div')[0]; oDiv.onmouseover = function () { changeAlpha(100); }; oDiv.onmouseout = function () { changeAlpha(30); }; var timer = null; var alpha = 30; function changeAlpha(isTarget) { clearInterval(timer); var speed = 0; timer = setInterval(function () { //注意这个速度判断要写在定时器里面 if (alpha < isTarget){ speed = 10; }else { speed = -10; } if (alpha == isTarget){ clearInterval(timer); }else { alpha += speed; oDiv.style.opacity = alpha/100; oDiv.style.filter = 'alpha(opacity:'+alpha+')'; } },30); } } </script></head><body><div></div></body></html>
3. Buffering movement
Gradually slows down and finally stops
The farther the distance, the greater the speed
The speed is determined by the distance
Speed = (target value - current value) / scaling factor
Math.ceil():向上取整 Math.ceil(3.41) 结果是4 ,Math.ceil(-9.8) 结果是 -9; Math.floor():向下取整 Math.floor(-0.9) 结果是 -1;
Example: Buffer menu
Bug: Speed rounding, decimals will cause trouble!!!
<html><head> <meta charset="utf-8"> <title>无标题文档</title> <style> *{ padding: 0; margin: 0; } #div1 {width:100px; height:100px; background:red; position:absolute; left:0; top:50px;} #div2 {width:1px; height:300px; position:absolute; left:300px; top:0; background:black;} </style> <script> function startMove() { var oDiv=document.getElementById('div1'); setInterval(function (){ var speed=(300-oDiv.offsetLeft)/10; //缓冲运动一定要取整,否则会出事的!!!! //Math.ceil():向上取整 Math.ceil(3.41) 结果是4 ,Math.ceil(-9.8) 结果是 -9; //Math.floor():向下取整 Math.floor(-0.9) 结果是 -1; //speed=Math.floor(speed); //速度大于0,向上取整,速度小于0,向下取整; speed=speed>0?Math.ceil(speed):Math.floor(speed); //速度不能为小数:速度里面有小数,导致oDiv.style.left的值带有小数,而oDiv.style.left会自动取整,导致他把小数抹掉了,导致误差!!! //故把速度向上取整,来避免此误差 oDiv.style.left=oDiv.offsetLeft+speed+'px'; document.title=oDiv.offsetLeft+','+speed; }, 30); } </script></head><body><input type="button" value="开始运动" onclick="startMove()" /><div id="div1"></div><div id="div2"></div></body></html>
Buffering movement one (there are compatibility issues on Chrome browser)
Buffering sidebar that follows page scrolling
Potential problem: When the target value is not an integer, it will If jitter occurs, just convert it to an integer! There may be an error of 0.5 pixels, which can be ignored!
suspended box on the right
Let’s learn some basic knowledge first
Get the scrolling distance of the browser scroll bar
1. When designing a page, the position of the fixed layer may often be used. This requires obtaining the coordinates of some html objects to set the coordinates of the target layer more flexibly. Attributes such as document.body.scrollTop may be used here, but the result of this attribute in an xhtml standard web page or, more simply, a page with a .> tag is 0. If this tag is not required, Then everything is normal, then how to get the coordinates of the body in the xhtml page? Of course there is a way - use document.documentElement to replace document.body, you can write like this
Example:
Get the scrolling distance of the browser scroll bar
var top = document.documentElement.scrollTop || document.body.scrollTop;
In JavaScript, || is a good thing. In addition to being used in if and other conditional judgments, it can also be used in variables Assignment. Then the above example is equivalent to the following example.
Example: var top = document.documentElement.scrollTop ? document.documentElement.scrollTop : document.body.scrollTop;
Writing like this can achieve good compatibility.
On the contrary, if no declaration is made, document.documentElement.scrollTop will be displayed as 0 instead.
document.body.clientWidth ==> BODY对象宽度document.body.clientHeight ==> BODY对象高度document.documentElement.clientWidth ==> 可见区域宽度document.documentElement.clientHeight ==> 可见区域高度 <html><head><meta charset="utf-8"><title>右侧悬浮窗</title><style>#div1 {width:100px; height:150px; background:red; position:absolute; right:0; bottom:0;}</style><script>window.onscroll=function (){ var oDiv=document.getElementById('div1'); var scrollTop=document.documentElement.scrollTop||document.body.scrollTop; //oDiv.style.top=document.documentElement.clientHeight-oDiv.offsetHeight+scrollTop+'px'; startMove(document.documentElement.clientHeight-oDiv.offsetHeight+scrollTop);};var timer=null;function startMove(iTarget){ var oDiv=document.getElementById('div1'); clearInterval(timer); timer=setInterval(function (){ var speed=(iTarget-oDiv.offsetTop)/4; speed=speed>0?Math.ceil(speed):Math.floor(speed); if(oDiv.offsetTop==iTarget) { clearInterval(timer); } else { oDiv.style.top=oDiv.offsetTop+speed+'px'; } }, 30);}</script></head><body style="height:2000px;"><div id="div1"></div></body></html>
Stop at a constant speed
//Absolute value,
Math.abs()
For example: (Math.abs(-6) ) and (Math.abs(6)) both result in 6. What he means is to change the value to have no sign, so it is all positive.
<html><head> <meta charset="utf-8"> <title>无标题文档</title> <style> #div1 {width:100px; height:100px; background:red; position:absolute; left:600px; top:50px;} #div2 {width:1px; height:300px; position:absolute; left:300px; top:0; background:black;} #div3 {width:1px; height:300px; position:absolute; left:100px; top:0; background:black;} </style> <script> var timer=null; function startMove(iTarget) { var oDiv=document.getElementById('div1'); clearInterval(timer); timer=setInterval(function (){ var speed=0; if(oDiv.offsetLeft<iTarget) { speed=10; } else { speed=-10; } //目标和物体之间的距离的绝对值小于等于速度,就算他达到目标了. if(Math.abs(iTarget-oDiv.offsetLeft)<=Math.abs(speed)) { clearInterval(timer); //目标和物体之间的有一小小的距离,计算误差导致的. //让left直接等于目标点 oDiv.style.left=iTarget+'px'; } else { oDiv.style.left=oDiv.offsetLeft+speed+'px'; } }, 30); } </script></head><body><input type="button" value="到100" onclick="startMove(100)" /><input type="button" value="到300" onclick="startMove(300)" /><div id="div1"></div><div id="div2"></div><div id="div3"></div></body></html>
In-depth basic application of JavaScript
The above is the detailed content of In-depth analysis of JavaScript and the movement of JS. For more information, please follow other related articles on the PHP Chinese website!

JavaScript's application in the real world includes front-end and back-end development. 1) Display front-end applications by building a TODO list application, involving DOM operations and event processing. 2) Build RESTfulAPI through Node.js and Express to demonstrate back-end applications.

The main uses of JavaScript in web development include client interaction, form verification and asynchronous communication. 1) Dynamic content update and user interaction through DOM operations; 2) Client verification is carried out before the user submits data to improve the user experience; 3) Refreshless communication with the server is achieved through AJAX technology.

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.


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

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

SublimeText3 Chinese version
Chinese version, very easy to use

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

Safe Exam Browser
Safe Exam Browser is a secure browser environment for taking online exams securely. This software turns any computer into a secure workstation. It controls access to any utility and prevents students from using unauthorized resources.

MinGW - Minimalist GNU for Windows
This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Mac version
God-level code editing software (SublimeText3)