好程序员 技术教程分享 JavaScript 运动框架,有需要的朋友可以参考下。
JavaScript 的运动,即让某元素的某些属性由一个值变到另一个值的过程。如让 div 的 width 属性由 200px 变到 400px , opacity 属性由 0.3 变到 1.0 ,就是一个运动过程。
实现运动要注意以下方面:
1. 匀速运动(改变 left 、 right 、 width 、 height 、 opacity 等属性)
2. 缓冲运动(速度是变化的)
3. 多物体运动(注意所有东西都不能共用,否则容易产生冲突,如定时器 timer )
4. 获取任意属性值(封装一个 getStyle 函数)
5. 链式运动(串行)
6. 同时运动(并行,同时改变多个属性,需要使用 json )
封装好的 getStyle 函数,在下面的运动框架中会用到:
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].οnmοuseοver=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);
});
})
})
来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/69913892/viewspace-2642286/,如需转载,请注明出处,否则将追究法律责任。
转载于:http://blog.itpub.net/69913892/viewspace-2642286/