欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  web前端

JS实现缓冲运动作用详解

程序员文章站 2022-04-07 10:29:51
...
这次给大家带来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>

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

推荐阅读:

ES6实现全屏滚动插件步骤详解

VueJs中V-bind指令怎样使用

以上就是JS实现缓冲运动作用详解的详细内容,更多请关注其它相关文章!