javascript运动函数

以’px’为单位的运动

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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
div {
width: 100px;
height: 50px;
background: red;
cursor: pointer;
margin-top: 20px;
font-size: 14px;
border: 0 solid #000;
}

</style>

</head>
<body>
<div></div>
<div></div>
<div>aaaaaaaaaaaaaa</div>
<div></div>

<script>
function getStyle (obj, attr){
if (obj.currentStyle) {
return obj.currentStyle;
} else {
return getComputedStyle(obj, false)[attr];
}
}

function startMove (obj, attr, iTarget){
// var oDiv = document.getElementById("div1");

clearInterval(obj.timer);

obj.timer = setInterval(function(){
var iCur = parseInt(getStyle(obj, attr));

var iSpeed = (iTarget-iCur)/8;
iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);

if (iCur === iTarget) {
clearInterval(obj.timer);
} else {
obj.style[attr] = iCur + iSpeed + "px";
}
}, 30);
}

window.onload = function (){
var aDiv = document.getElementsByTagName("div");
var i = 0;

aDiv[0].onclick = function (){
startMove(this, 'width', 300);
}

aDiv[1].onclick = function (){
startMove(this, 'height', 200);
}

aDiv[2].onclick = function (){
startMove(this, 'font-size', 100);
}
aDiv[3].onclick = function (){
startMove(this, 'borderWidth', 100);
}

}
</script>

</body>
</html>