Home > Web Front-end > JS Tutorial > js animation achieves uniform motion in one direction within a specified time

js animation achieves uniform motion in one direction within a specified time

巴扎黑
Release: 2017-07-20 14:16:18
Original
1117 people have browsed it

The specific code is as follows

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <style>
        *{
            margin:0;
            padding:0;
        }
        #box{
            position:absolute;
            top:0;
            left:0;
            padding:0;
            width:100px;
            height:100px;
            background:lightblue;

        }</style>
</head>
<body>
    <div id=&#39;box&#39;></div>
    <script>//思想1:var oBox = document.getElementById('box');//实现一个匀速运动:在指定时间内完成动画:计算出总距离/总时间,然后求出对应的步长(每10ms走一步的话需要走多远)var maxLeft = (document.documentElement.clientWidth || document.body.clientWidth) - oBox.offsetWidth;var duration = 2000;var step = (maxLeft/duration)*10;var timer = window.setInterval(function(){var curLeft = utils.css(oBox,"left");
            curLeft+=step;if(curLeft>=maxLeft){
                window.clearInterval(timer);return;
            }
            utils.css(oBox,"left",curLeft);
        },10)//思想2:function Linear(t,b,c,d){//相对应的是time begin change durationreturn c*t/d+b        }var oBox = document.getElementById('box');var target = (document.documentElement.clientWidth || document.body.clientWidth) - oBox.offsetWidth;var begin = utils.css(oBox,'left'),change = target-begin;var duration = 2000,time = null;var timer = window.setInterval(function(){
            time+=10;if(time>=duration){
                utils.css(oBox,"left",target);
                window.clearInterval(timer);return;
            }var curPos = Linear(time,begin,change,duration);
            utils.css(oBox,"left",curPos)

        },10)</script>
</body>
</html>
Copy after login

The above is the detailed content of js animation achieves uniform motion in one direction within a specified time. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template