<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>js运动</title>
<style type="text/css">
html,body{
height:100%; margin:0; padding:0; position:relative;
}
#demo,#down,#right{
width:100px; height:100px; position:absolute; left:0; top:0;
background-color:skyblue;text-align: center;line-height: 100px;
}
</style>
<script>
function Animate(_element){
this.hz=30;
this.calculate=function(_css,_time){
this.times=_time/this.hz;
if(_css.left){
this.hs=(Number(_css.left.match(/\d+/g)[0])-_element.offsetLeft)/this.times;
}
if(_css.top){
this.vs=(Number(_css.top.replace(/\px/g,""))-_element.offsetTop)/this.times;
}
}
this.start=function(_css,_time){
var _me=this;
var count=1;
this.calculate(_css,_time);
this.timer=window.setInterval(function(){
if(_css.left){
_element.style.left=_element.offsetLeft+_me.hs+"px";
}
if(_css.top){
_element.style.top=_element.offsetTop+_me.vs+"px";
}
if(count++>=_me.times){
clearInterval(_me.timer);
}
},this.hz)
}
}
window.onload=function(){
var _a=new Animate(document.getElementById("demo"));
_a.start({
left:"800px",
top:"600px"
},600)
var _r=new Animate(document.getElementById("right"));
_r.start({
left:"800px"
},300)
var _d=new Animate(document.getElementById("down"));
_d.start({
top:"600px"
},1000)
};
</script>
</head>
<body>
<div id="demo">右下</div>
<div id="right">右</div>
<div id="down">下</div>
</body>
</html>