本文实例讲述了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>www.uoften.com JS缓冲运动</title>
<style>
#div{
  width:150px;
  height:150px;
  background:#0C6;
  position:absolute;
  left:0;
  top:50px;
}
#div2{
  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 div = document.getElementById('div');
  clearInterval(time);
  time = setInterval(function(){
    //改变位置,如果向左则e==500, 向上取整, 否则向右,向下取整,速度=(终点位置 - 当前位置)/一个数
    e==500 ? speed = Math.ceil((e-(div.offsetLeft))/30):speed = Math.floor((e-(div.offsetLeft))/30)
    if (e <= div.style.left){//达到,关闭定时器
      clearInterval(time);
    }
    else
    {
      div.style.left = div.offsetLeft+speed+'px';
    }
  },30);
};
</script>
<body>
<input type="button" value="向右运动" id="btn" />
<input type="button" value="向左运动" id="btn2" />
<div id = "div">
</div>
<div id = "div2">
</div>
</body>
</html>

点击此处查看在线演示效果。

或者使用本站在线HTML/js运行工具测试查看运行效果:http://tools.uoften.com/code/HtmlJsRun

更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《JavaScript运动效果与技巧汇总》、《JavaScript切换特效与技巧总结》、《JavaScript查找算法技巧总结》、《JavaScript动画特效与技巧汇总》、《JavaScript错误与调试技巧总结》、《JavaScript数据结构与算法技巧总结》、《JavaScript遍历算法与技巧总结》及《JavaScript数学运算用法总结》

希望本文所述对大家JavaScript程序设计有所帮助。

点赞(139)

评论列表共有 0 条评论

立即
投稿
返回
顶部