javascript
好程序员技术教程分享JavaScript运动框架
好程序員技術(shù)教程分享JavaScript運動框架,有需要的朋友可以參考下。
JavaScript的運動,即讓某元素的某些屬性由一個值變到另一個值的過程。如讓div的width屬性由200px變到400px,opacity屬性由0.3變到1.0,就是一個運動過程。
實現(xiàn)運動要注意以下方面:
封裝好的getStyle函數(shù),在下面的運動框架中會用到:
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; //標(biāo)志變量,為true表示所有運動都到達目標(biāo)值
clearInterval(obj.timer);
obj.timer=setInterval(function(){
flag=true;
for(var attr in json){
//獲取當(dāng)前值
var curr=0;
if(attr=='opacity'){
curr=Math.round(parseFloat(getStyle(obj,attr))*100); //parseFloat可解析字符串返回浮點數(shù)//round四舍五入
}
else{
curr=parseInt(getStyle(obj,attr)); //parseInt可解析字符串返回整數(shù)
}
//計算速度
var speed=(json[attr]-curr)/10;
speed=speed>0?Math.ceil(speed):Math.floor(speed);
//檢測是否停止
if(curr!=json[attr]){
flag=false; //有一個屬性未達目標(biāo)值,就把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);
}
調(diào)用上述運動框架的實例:
var div_icon=document.getElementById('icon');
var aList=div_icon.getElementsByTagName('a');
for(var i=0;i aList[i].οnmοuseοver=function(){
var _this=this.getElementsByTagName('i')[0];
Move(_this,{top:-70,opacity:0},function(){
_this.style.top=30+'px';
Move(_this,{top:10,opacity:100});
});
}
}
好了,以上就是用JavaScript編寫的運動框架。此外,jQuery中的animate函數(shù)也可以方便實現(xiàn)上述功能:
$(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);
});
})
})
總結(jié)
以上是生活随笔為你收集整理的好程序员技术教程分享JavaScript运动框架的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 梦到收衣服什么意思
- 下一篇: SpringBoot部署项目到Docke