96游戏网
您的当前位置:首页怎样使用JS实现缓冲运动

怎样使用JS实现缓冲运动

来源:96游戏网


这次给大家带来怎样使用JS实现缓冲运动,使用JS实现缓冲运动的注意事项有哪些,下面就是实战案例,一起来看一下。

缓冲需要用到数值取整,向上取整:Math.ceil() 向下取整Math.floor()

移动的速度慢慢减慢的效果,移动速度=(终点位置 - 当前位置) / 一个数

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>JS缓冲运动</title>
<style>
#p{
 width:150px;
 height:150px;
 background:#0C6;
 position:absolute;
 left:0;
 top:50px;
}
#p2{
 background:#000;
 height:600px;
 position:absolute;
 left:500px;
 width:2px;
}
</style>
</head>
<script>
var speed;
var time;
window.onload = function(){
 var btn = document.getElementById('btn');
 btn.onclick = function(){
 speed = 0;
 move(500);
 };
 btn2.onclick = function(){
 speed = 0;
 move(0);
 };
};
function move(e){
 var p = document.getElementById('p');
 clearInterval(time);
 time = setInterval(function(){
 //改变位置,如果向左则e==500, 向上取整, 否则向右,向下取整,速度=(终点位置 - 当前位置)/一个数
 e==500 ? speed = Math.ceil((e-(p.offsetLeft))/30):speed = Math.floor((e-(p.offsetLeft))/30)
 if (e <= p.style.left){//达到,关闭定时器
 clearInterval(time);
 }
 else
 {
 p.style.left = p.offsetLeft+speed+'px';
 }
 },30);
};
</script>
<body>
<input type="button" value="向右运动" id="btn" />
<input type="button" value="向左运动" id="btn2" />
<p id = "p">
</p>
<p id = "p2">
</p>
</body>
</html>

相信看了本文案例你已经掌握了方法,更多精彩请关注Gxl网其它相关文章!

推荐阅读:

怎样实现Vue项目中使用Vux

不用JS实现菜单打开关闭

显示全文