<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>多物体运动2</title>
<style>
div {
font-size: 14px;
width: 100px;
height: 50px;
background: red;
margin: 10px;
border: 1px solid black;
}
</style>
<script>
window.onload = function() {
var aDiv = document.getElementsByTagName('div');
aDiv[0].onclick = function() {
startMove(this, 'width', 300);
}
aDiv[1].onclick = function() {
startMove(this, 'height', 300);
}
aDiv[2].onclick = function() {
startMove(this, 'fontSize', 100);
}
aDiv[3].onclick = function() {
startMove(this, 'borderWidth', 100);
}
}
function getStyle(obj, attr) { //获取行内样式
if (obj.currentStyle) {
return obj.currentStyle[attr];
} else {
return getComputedStyle(obj, false)[attr];
}
}
var timer = null;
function startMove(obj, attr, iTarget) {
clearInterval(obj.timer);
obj.timer = setInterval(function() {
var iCur = parseInt(getStyle(obj, attr));
var iSpeed = (iTarget - iCur) / 8;
iSpeed = iSpeed > 0 ? Math.ceil(iSpeed) : Math.floor(iSpeed);
if (iCur == iTarget) {
clearInterval(obj.timer);
} else {
obj.style[attr] = iCur + iSpeed + 'px';
}
}, 30)
}
</script>
</head>
<body>
<div></div>
<div></div>
<div>sdfsf</div>
<div></div>
</body>
</html>