简单版时间运动框架
.box{
width: 100px;
height: 100px;
background-color: pink;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script>
var oBox =document.getElementsByClassName("box")[0];
animation(oBox,"width",500,100);
function animation(ele,attr,value,time,) {
var gotime = new Date().getTime();
var startValue =parseFloat(getstyle(ele)[attr]);
var change= value-startValue;
function fn() {
var now =(new Date().getTime()-gotime)/time;
if (now>=1){
now =1;
ele.style[attr]=startValue +now*change+"px";
}else{
ele.style[attr]=startValue +now*change+"px";
requestAnimationFrame(fn);
}
}
fn();
}
function getstyle(ele) {
return ele.currentStyle ||getComputedStyle(ele);
}
</script>
基础班运动框架 可以同时改变多个属性值
.box{
width: 100px;
height: 100px;
background-color: pink;
opacity: 0;
}
</style>
</head>
<body>
<div class="box"></div>
</body>
<script>
var oBox =document.getElementsByClassName("box")[0];
animation(oBox,{
width:500,
height:500,
opacity:1,
transform:function (now,key) {
this.style[key]=`rotate(${parseInt(360*now)}deg) rotateX(${parseInt(360*now)}deg) rotateY(${parseInt(360*now)}deg)`;
},
background:function (now,key) {
var color =[
Math.floor(Math.random()*256),
Math.floor(Math.random()*256),
Math.floor(Math.random()*256),
];
this.style[key] =`rgb(`+color.join(",")+`)`;
}
},500);
function animation(ele,attr,time,callback) {
var gotime=new Date().getTime(),
startAttr ={};
for (var key in attr) {
if (typeof attr[key] === "function") {
startAttr[key] = attr[key];
}else {
var start = parseFloat(getstyle(ele)[key]),
change = parseFloat(attr[key]) - start;
if (change !== 0) {
startAttr[key] = {
start: start,
change: change
};
}
}
}
function fn() {
var now =(new Date().getTime()-gotime)/time;
if (now >=1){
now =1;
setstyle(ele,startAttr,now);
} else{
setstyle(ele,startAttr,now);
requestAnimationFrame(fn);
}
}
fn();
}
function setstyle(ele,startAttr,now) {
for(var key in startAttr){
if (key==="opacity"){
ele.style[key] = startAttr[key].start+startAttr[key].change*now;
}else if (typeof startAttr[key]==="function") {
startAttr[key].call(ele,now,key);
} else{
ele.style[key] = startAttr[key].start+startAttr[key].change*now+"px";
}
}
}
function getstyle(ele) {
return ele.currentStyle ||getComputedStyle(ele);
}
</script>