标签:
1. 物体掉落
1 window.onload = startMove;
2
3 var iSpeedX = 100;
4 var iSpeedY = 8;
5
6 function startMove() {
7 setInterval(function() {
8 var oDiv = document.getElementById("div1");
9
10 //加重力
11 iSpeedY += 5;
12
13 var l = oDiv.offsetLeft + iSpeedX;
14 var t = oDiv.offsetTop + iSpeedY;
15
16 //防止出界
17 if (l >= document.documentElement.clientWidth - oDiv.offsetWidth) {
18 iSpeedX *= -0.8;
19 l = document.documentElement.clientWidth - oDiv.offsetWidth;
20 } else if (l <= 0) {
21 iSpeedX *= -0.8;
22 l = 0;
23 }
24
25 if (t >= document.documentElement.clientHeight - oDiv.offsetHeight) {
26 iSpeedY *= -0.8;
27 iSpeedX *= 0.8;
28 t = document.documentElement.clientHeight - oDiv.offsetHeight;
29 } else if (t <= 0) {
30 iSpeedY *= -0.8;
31 iSpeedX *= 0.8;
32 t = 0;
33 }
34
35 //解决小数为负数不停止滑动的问题
36 if (Math.abs(iSpeedX) < 1) {
37 iSpeedX = 0;
38 }
39
40 if (Math.abs(iSpeedY) < 1) {
41 iSpeedY = 0;
42 }
43
44 oDiv.style.left = l + "px";
45 oDiv.style.top = t + "px";
46 }, 30);
47 }
2. 抛扔物体
1 window.onload = function() {
2 var oDiv = document.getElementById("div1");
3 var lastX = 0;
4 var lastY = 0;
5
6 oDiv.onmousedown = function(ev) {
7 clearInterval(timer);
8
9 var oEvent = ev || event;
10 var disX = oEvent.clientX - oDiv.offsetLeft;
11 var disY = oEvent.clientY - oDiv.offsetTop;
12
13 document.onmousemove = function(ev) {
14 var oEvent = ev || event;
15
16 var l = oEvent.clientX - disX;
17 var t = oEvent.clientY - disY;
18
19 oDiv.style.left = l + "px";
20 oDiv.style.top = t + "px";
21
22 //计算时刻位移来获取速度
23 iSpeedX = l - lastX;
24 iSpeedY = t - lastY;
25
26 lastX = l;
27 lastY = t;
28 };
29
30 document.onmouseup = function() {
31 document.onmousemove = null;
32 document.onmouseup = null;
33 startMove();
34 };
35 };
36 };
37 var timer = null;
38 var iSpeedX = 0;
39 var iSpeedY = 0;
40
41 function startMove() {
42 clearInterval(timer);
43 timer = setInterval(function() {
44 var oDiv = document.getElementById("div1");
45
46 //加重力
47 iSpeedY += 5;
48
49 var l = oDiv.offsetLeft + iSpeedX;
50 var t = oDiv.offsetTop + iSpeedY;
51
52 //防止出界
53 if (l >= document.documentElement.clientWidth - oDiv.offsetWidth) {
54 iSpeedX *= -0.8;
55 l = document.documentElement.clientWidth - oDiv.offsetWidth;
56 } else if (l <= 0) {
57 iSpeedX *= -0.8;
58 l = 0;
59 }
60
61 if (t >= document.documentElement.clientHeight - oDiv.offsetHeight) {
62 iSpeedY *= -0.8;
63 iSpeedX *= 0.8;
64 t = document.documentElement.clientHeight - oDiv.offsetHeight;
65 } else if (t <= 0) {
66 iSpeedY *= -0.8;
67 iSpeedX *= 0.8;
68 t = 0;
69 }
70
71 //解决小数为负数不停止滑动的问题
72 if (Math.abs(iSpeedX) < 1) {
73 iSpeedX = 0;
74 }
75
76 if (Math.abs(iSpeedY) < 1) {
77 iSpeedY = 0;
78 }
79
80 //运动终止条件
81 if (iSpeedX == 0 && iSpeedY == 0
82 && t == document.documentElement.clientHeight - oDiv.offsetHeight) {
83 clearInterval(timer);
84 } else {
85 oDiv.style.left = l + "px";
86 oDiv.style.top = t + "px";
87 }
88 }, 30);
89 }
标签:
原文地址:http://www.cnblogs.com/HuoAA/p/5074163.html