1. 弹性运动公式
1 window.onload = function() {
2 var oDiv = document.getElementById("div1");
3 var iSpeed = 0;
4
5 setInterval(function() {
6 //弹性运动
7 iSpeed += (300 - oDiv.offsetLeft) / 5;
8
9 //摩擦力
10 iSpeed *= 0.7;
11
12 oDiv.style.left = oDiv.offsetLeft + iSpeed + "px";
13 }, 30);
14 };
2. 应用 - 弹性导航
1 window.onload = function() {
2 var oUl = document.getElementById("ul1");
3 var aLi = document.getElementsByTagName("li");
4 var oBg = aLi[aLi.length - 1];
5
6 for (var i = 0; i < aLi.length - 1; i++) {
7 aLi[i].onmouseover = function() {
8 startMove(oBg, this.offsetLeft);
9 };
10 }
11 };
12
13 var iSpeed = 0;
14 var left = 0;
15
16 function startMove(obj, iTarget) {
17 clearInterval(obj.timer);
18 obj.timer = setInterval(function() {
19 iSpeed += (iTarget - obj.offsetLeft) / 5;
20 iSpeed *= 0.7;
21
22 //处理小数误差的问题
23 if (Math.abs(iSpeed) < 1 && Math.abs(iTarget - left) < 1) {
24 clearInterval(obj.timer);
25 obj.style.left = iTarget + "px";
26 } else {
27 left+=iSpeed;
28 obj.style.left = left + "px";
29 }
30 }, 30);
31 }
3. 应用 - 弹性菜单,注意运动越界
1 window.onload = function() {
2 var oDiv = document.getElementById("div1");
3 oDiv.onmouseover = function() {
4 startMove(this, 300);
5 };
6
7 oDiv.onmouseout = function() {
8 startMove(this, 50);
9 };
10 };
11
12 var iSpeed = 0;
13 var height = 0;
14
15 function startMove(obj, iTarget) {
16 clearInterval(obj.timer);
17 obj.timer = setInterval(function() {
18 iSpeed += (iTarget - obj.offsetHeight) / 5;
19 iSpeed *= 0.7;
20
21 if (Math.abs(iSpeed) < 1 && Math.abs(iTarget - height) < 1) {
22 clearInterval(obj.timer);
23 obj.style.height = iTarget + "px";
24 } else {
25 height += iSpeed;
26
27 //防止运动过界,height 没有负数
28 height = height < 0 ? 0 : height;
29 obj.style.height = height + "px";
30 }
31 }, 30);
32 }