温馨提示×

温馨提示×

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

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

js之运动框架缓冲运动

发布时间:2020-06-29 12:42:18 来源:网络 阅读:369 作者:水滴的历程 栏目:软件技术

由于JS里对于数值小数点会自动去除,所以对于运动位置,需要使用Math.ceil()向上取整或者

Math.floor()向下取整进行解决

以下是我的缓冲运动练习简单代码

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>无标题文档</title>
<style>
#div1{width:200px;height:200px;background:red;left:0px;top:50px;position:absolute;}
#div2{width:1px;height:250px;background:black;left:400px;top:20px;position:absolute;}
</style>
<script>
window.onload=function ()
{
	var oDiv=document.getElementById('div1');
	var oBtn=document.getElementById('btn1');
	oBtn.onclick=function ()
	{
		startMove(400);	
		
	}
};
var timer=null;
function startMove(target)
{
	var oDiv=document.getElementById('div1');
	var speed=0;
	clearInterval(timer)
	
	timer=setInterval(function ()
	{
			//speed会被直接取整,舍去余数,所以位置不精确,需要通过向上取整Math.ceil()来解决
			speed=Math.ceil((target-oDiv.offsetLeft)/10);   
			oDiv.style.left=oDiv.offsetLeft+speed+'px';	
			document.title=oDiv.offsetLeft+','+speed;
	},30);
};
</script>
</head>

<body>
<input id="btn1" type="button" value="开始运动" />
<div id="div1">
</div>
<div id="div2">
</div>
</body>
</html>


向AI问一下细节

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

AI