具体代码如下
<!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='box'></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>
以上就是js动画之在指定时间内实现单方向匀速运动的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号