简单的入门小动画

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<style>
#div1{height:100px;100px;position:absolute;top:50px;left:10px;background:red;}
</style>
<body>
<input type="button" value="向前" id = 'btn1'>
<div id="div1"></div>
<script>
function getEle(_id){
return document.getElementById(_id);
}
var oBtn1 = getEle('btn1');
var oDiv = getEle('div1');
oBtn1.onclick = function(){
doMove(oDiv,'left', 12, 800, function(){doMove(oDiv, 'top', 12, 300)});
}
function doMove(obj, attr, dir, target, func){
dir = parseInt(getStyle(obj, attr)) < target ? dir : -dir;
clearInterval(obj.timer);
obj.timer = setInterval(function(){
var speed = parseInt(getStyle(obj,attr)) + dir;
if(speed > target && dir > 0 || speed < target && dir < 0){
speed = target;
}
obj.style[attr] = speed + 'px';
if(speed == target){
clearInterval(obj.timer);
func && func();
}
},30)

}
function getStyle(obj,attr){
return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle(obj)[attr];
}

</script>
</body>
</html>

原文地址:https://www.cnblogs.com/clearfix/p/4154213.html