Home Web Front-end JS Tutorial In-depth analysis of JavaScript and the movement of JS

In-depth analysis of JavaScript and the movement of JS

Mar 13, 2018 pm 01:38 PM
javascript js

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(&#39;div1&#39;);            //为了保证只有一个定时器工作,把之前的定时器全关了
            clearInterval(timer);
            timer=setInterval(function (){                var speed=1;                if(oDiv.offsetLeft>=300)
                {
                    clearInterval(timer);
                }                else
                {
                    oDiv.style.left=oDiv.offsetLeft+speed+&#39;px&#39;;
                }
            }, 30);
        }    </script><input><div></div>
Copy after login

In-depth analysis of JavaScript and the movement of JS

<!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(&#39;div1&#39;);
    
    oDiv.onmouseover=function ()    {
        startMove(0);
    };
    oDiv.onmouseout=function ()    {
        startMove(-150);
    };
};var timer=null;function startMove(iTarget){    var oDiv=document.getElementById(&#39;div1&#39;);
    
    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+&#39;px&#39;;
        }
    }, 30);
}</script></head><body><div id="div1">
    <span>分享到</span></div></body></html>
Copy after login

In-depth analysis of JavaScript and the movement of JS

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(&#39;div&#39;)[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 = &#39;alpha(opacity:&#39;+alpha+&#39;)&#39;;
                    }
                },30);
            }
        }    </script></head><body><div></div></body></html>
Copy after login

In-depth analysis of JavaScript and the movement of JS

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;
Copy after login

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(&#39;div1&#39;);            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+&#39;px&#39;;                document.title=oDiv.offsetLeft+&#39;,&#39;+speed;            }, 30);        }    </script></head><body><input type="button" value="开始运动" onclick="startMove()" /><div id="div1"></div><div id="div2"></div></body></html>
Copy after login

In-depth analysis of JavaScript and the movement of JS

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(&#39;div1&#39;);    var scrollTop=document.documentElement.scrollTop||document.body.scrollTop;        //oDiv.style.top=document.documentElement.clientHeight-oDiv.offsetHeight+scrollTop+&#39;px&#39;;    startMove(document.documentElement.clientHeight-oDiv.offsetHeight+scrollTop);};var timer=null;function startMove(iTarget){    var oDiv=document.getElementById(&#39;div1&#39;);        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+&#39;px&#39;;        }    }, 30);}</script></head><body style="height:2000px;"><div id="div1"></div></body></html>
Copy after login

In-depth analysis of JavaScript and the movement of JS

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(&#39;div1&#39;);
            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+&#39;px&#39;;
                }                else
                {
                    oDiv.style.left=oDiv.offsetLeft+speed+&#39;px&#39;;
                }
            }, 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>
Copy after login

In-depth analysis of JavaScript and the movement of JS

## I believe you have mastered the method after reading the case in this article. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Recommended reading:

In-depth basic application of JavaScript

##8 basic knowledge that must be paid attention to in JS

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

Recommended: Excellent JS open source face detection and recognition project Recommended: Excellent JS open source face detection and recognition project Apr 03, 2024 am 11:55 AM

Face detection and recognition technology is already a relatively mature and widely used technology. Currently, the most widely used Internet application language is JS. Implementing face detection and recognition on the Web front-end has advantages and disadvantages compared to back-end face recognition. Advantages include reducing network interaction and real-time recognition, which greatly shortens user waiting time and improves user experience; disadvantages include: being limited by model size, the accuracy is also limited. How to use js to implement face detection on the web? In order to implement face recognition on the Web, you need to be familiar with related programming languages ​​and technologies, such as JavaScript, HTML, CSS, WebRTC, etc. At the same time, you also need to master relevant computer vision and artificial intelligence technologies. It is worth noting that due to the design of the Web side

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Essential tools for stock analysis: Learn the steps to draw candle charts with PHP and JS Dec 17, 2023 pm 06:55 PM

Essential tools for stock analysis: Learn the steps to draw candle charts in PHP and JS. Specific code examples are required. With the rapid development of the Internet and technology, stock trading has become one of the important ways for many investors. Stock analysis is an important part of investor decision-making, and candle charts are widely used in technical analysis. Learning how to draw candle charts using PHP and JS will provide investors with more intuitive information to help them make better decisions. A candlestick chart is a technical chart that displays stock prices in the form of candlesticks. It shows the stock price

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts PHP and JS Development Tips: Master the Method of Drawing Stock Candle Charts Dec 18, 2023 pm 03:39 PM

With the rapid development of Internet finance, stock investment has become the choice of more and more people. In stock trading, candle charts are a commonly used technical analysis method. It can show the changing trend of stock prices and help investors make more accurate decisions. This article will introduce the development skills of PHP and JS, lead readers to understand how to draw stock candle charts, and provide specific code examples. 1. Understanding Stock Candle Charts Before introducing how to draw stock candle charts, we first need to understand what a candle chart is. Candlestick charts were developed by the Japanese

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

See all articles