這篇文章主要為大家詳細介紹了原生js仿jquery animate動畫效果,具有一定的,感興趣的小伙伴們可以參考一下
代碼如下:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>動畫</title>
<style>
*{margin:0;padding:0;}
.box{width: 400px;height: 300px;background: #000;margin:40px auto;color: #fff;font-size: 18px;text-align: center;}
</style>
<script>
//獲取對象樣式規(guī)則信息,IE下使用currentStyle
function getStyle(obj,style){
return obj.currentStyle?obj.currentStyle[style]:getComputedStyle(obj,false)[style];
}
//原生js動畫類似jquery--animate
function animate(obj,styleJson,callback){
clearInterval(obj.timer);
// 開啟定時器
obj.timer=setInterval(function(){
var flag=true;//假設(shè)所有動作都已完成成立。
for(var styleName in styleJson){
//1.取當(dāng)前屬性值
var iMov=0;
// 透明度是小數(shù),所以得單獨處理
iMov=styleName=='opacity'?Math.round(parseFloat(getStyle(obj,styleName))*100):parseInt(getStyle(obj,styleName));
//2.計算速度
var speed=0;
speed=(styleJson[styleName]-iMov)/8;//緩沖處理,這邊也可以是固定值
speed=speed>0?Math.ceil(speed):Math.floor(speed);//區(qū)分透明度及小數(shù)點,向上取整,向下取整
//3.判斷是否到達預(yù)定值
if(styleJson[styleName]!=iMov){
flag=false;
if(styleName=='opacity'){//判斷結(jié)果是否為透明度
obj.style[styleName]=(iMov+speed)/100;
obj.style.filter='alpha(opacity:'+(iMov+speed)+')';
}else{
obj.style[styleName]=iMov+speed+'px';
}
}
}
if(flag){//到達設(shè)定值,停止定時器,執(zhí)行回調(diào)
clearInterval(obj.timer);
if(callback){callback();}
}
},30)
}
window.onload=function(){
document.getElementById('box').onclick=function(){
var oThis=this;
animate(oThis,{'width':'500'},function(){
animate(oThis,{'height':'400'},function(){alert('寬度高度都增加了')});
});
}
}
</script>
</head>
<body>
<div class="box" id="box">點擊效果:寬度增加->高度增加->彈出框</div>
</body>
</html>
注意點
1.動畫前要先停止原來的定時器,不然綁定多個對象的話會沖突
2.定時器的id要區(qū)分開,不能重疊,這里我直接那綁定對象的 對象來賦值 obj.timer
3.要判斷所要執(zhí)行的動畫,是否全部到了設(shè)定值=> flag,全部執(zhí)行完再停止定時器再執(zhí)行回調(diào)函數(shù)
4.javascript的數(shù)據(jù)類型轉(zhuǎn)換問題
alert(0.07*100);
//彈出7.000000000000001
注意:Javascript在存儲時并不區(qū)分number和float類型,而是統(tǒng)一按float存儲。而javascript使用IEEE 754-2008 標準定義的64bit浮點格式存儲number,按照IEEE 754的定義:
decimal64對應(yīng)的整形部分長度為 10,小數(shù)部分長度為16,所以默認的計算結(jié)果為“7.0000000000000001”,如最后一個小數(shù)為0,則取1作為有效數(shù)字標志。
5.傳入的json數(shù)據(jù)不能帶px,例如{'width':'300px'},為了兼容透明度的數(shù)值,沒想到好的處理方式,有沒有大神指導(dǎo)下...
6.該定時器做了緩沖處理,變化越來越慢,想要快速的效果或者勻速的效果,只需要在2.計算速度那塊做下處理就可以
7.不兼容css3的屬性,只兼容了(width,height,top,left,right,bottom,opacity)
8.獲取對象樣式的信息,要判斷IE或者火狐瀏覽器,區(qū)別對待
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助