JS简单动画封装
Posted ljy0414
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS简单动画封装相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
*{
margin: 0;
padding:0;
}
.box{
width: 100px;
height: 100px;
border:1px solid red;
background-color: #FA5B5B;
position: relative;
left: 100px;
top: 100px;
opacity: 1;
}
</style>
</head>
<body>
<div class="box" id="box"></div>
<script type="text/javascript">
var obox = document.getElementById("box");
function animate(elem,targetJSON,time){
var count = 0;
var interval = 50;
var nowJSON = {};
var maxcount = time/interval;//次数
for(var k in targetJSON){
nowJSON[k] = parseFloat(Fecehcomputerstyle(elem,k));
}
var stepJSON = {};
for(var k in targetJSON){
targetJSON[k] = parseFloat(targetJSON[k]);
stepJSON[k] = parseFloat((targetJSON[k]-nowJSON[k])/maxcount);
}
console.log(nowJSON);
console.log(targetJSON);
console.log(stepJSON);
var timer = setInterval(function(){
for(var k in nowJSON){
nowJSON[k] += stepJSON[k];
if(k != "opacity"){
elem.style[k] = nowJSON[k] + "px";}
else{
elem.style[k] = nowJSON[k];
}
// console.log(elem.style[k]);
}
count++;
if(count == maxcount){
if(k != "opacity"){
elem.style[k] = targetJSON[k] + "px";}
else{
elem.style[k] = targetJSON[k];;
}
clearInterval(timer);
}
},interval);
function Fecehcomputerstyle(obj,property){
if(window.getComputedStyle){
return window.getComputedStyle(obj)[property];
}else{
return obj.currentStyle[property];
}//轮子
}
}
animate(obox,{"opacity":0.1},6000);
</script>
</body>
</html>
以上是关于JS简单动画封装的主要内容,如果未能解决你的问题,请参考以下文章