好程序員技術教程分享JavaScript運動框架,有須要的朋友能夠參考下。css
JavaScript的運動,即讓某元素的某些屬性由一個值變到另外一個值的過程。如讓div的width屬性由200px變到400px,opacity屬性由0.3變到1.0,就是一個運動過程。程序員
實現運動要注意如下方面:json
1. 勻速運動(改變left、right、width、height、opacity等屬性)框架
2. 緩衝運動(速度是變化的)函數
3. 多物體運動(注意全部東西都不能共用,不然容易產生衝突,如定時器timer)動畫
4. 獲取任意屬性值(封裝一個getStyle函數)this
5. 鏈式運動(串行)spa
6. 同時運動(並行,同時改變多個屬性,須要使用 json)教程
封裝好的getStyle函數,在下面的運動框架中會用到:seo
function getStyle(obj,attr){
if(obj.currentStyle){
return obj.currentStyle[attr]; //針對IE
}
else{
return getComputedStyle(obj,false)[attr]; //針對Firefox
}
}
萬能的運動框架:
function Move(obj,json,callback){
var flag=true; //標誌變量,爲true表示全部運動都到達目標值
clearInterval(obj.timer);
obj.timer=setInterval(function(){
flag=true;
for(var attr in json){
//獲取當前值
var curr=0;
if(attr=='opacity'){
curr=Math.round(parseFloat(getStyle(obj,attr))*100); //parseFloat可解析字符串返回浮點數//round四捨五入
}
else{
curr=parseInt(getStyle(obj,attr)); //parseInt可解析字符串返回整數
}
//計算速度
var speed=(json[attr]-curr)/10;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
//檢測是否中止
if(curr!=json[attr]){
flag=false; //有一個屬性未達目標值,就把flag變成false
}
if(attr=='opacity'){
obj.style.filter='alpha(opacity:'+(curr+speed)+')'; //針對IE
obj.style.opacity=(curr+speed)/100; //針對Firefox和Chrome
}
else{
obj.style[attr]=curr+speed+'px';
}
}
if(flag){
clearInterval(obj.timer);
if(callback){
callback();
}
}
},30);
}
調用上述運動框架的實例:
var div_icon=document.getElementById('icon');
var aList=div_icon.getElementsByTagName('a');
for(var i=0;i<aList.length;i++){
<span style="white-space:pre"> </span>aList[i].onmouseover=function(){
<span style="white-space:pre"> </span>var _this=this.getElementsByTagName('i')[0];
<span style="white-space:pre"> </span>Move(_this,{top:-70,opacity:0},function(){
<span style="white-space:pre"> </span>_this.style.top=30+'px';
<span style="white-space:pre"> </span>Move(_this,{top:10,opacity:100});
<span style="white-space:pre"> </span>});
<span style="white-space:pre"> </span>}
}
好了,以上就是用JavaScript編寫的運動框架。此外,jQuery中的animate函數也能夠方便實現上述功能:
$(function(){
$('#icon a').mouseenter(function(){
$(this).find('i').animate({top:"-70px",opacity:"0"}, 300,function(){ //動畫速度爲300ms
$(this).css({top:"30px"});
$(this).animate({top:"10px",opacity:"1"}, 200);
});
})
})