由于JS里对于数值小数点会自动去除,所以对于运动位置,需要使用Math.ceil()向上取整或者
Math.floor()向下取整进行解决
以下是我的缓冲运动练习简单代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
<
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
>
|
本文转自 水滴的历程 51CTO博客,原文链接:http://blog.51cto.com/12390959/1907149