温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

JS实现的缓冲运动效果示例

发布时间:2020-08-21 22:57:12 来源:脚本之家 阅读:134 作者:珍惜每分每秒 栏目:web开发

本文实例讲述了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.jb51.net 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.jb51.net/code/HtmlJsRun

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

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

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI