JavaScript常用封装函数
基本运动
function doMove(obj,attr,speed,target,endFn){
var iCur = getStyle( obj, attr );
speed = iCur <= target ? Math.abs(speed) : -Math.abs(speed);
clearInterval(obj.timer);
obj.timer = setInterval(function(){
iCur = getStyle( obj, attr ) + speed;
if( (speed > 0 && iCur >= target) || (speed < 0 && iCur <= target) ){
iCur = target;
}
obj.style[attr] = iCur + 'px';
if(iCur == target){
clearInterval(obj.timer);
if( typeof endFn === 'function' ){ endFn(); }
}
},30);
}
透明度变化
function opacity(obj,speed,target,endFn){
var iCur = getStyle( obj, 'opacity' ) * 100;
speed = iCur <= target ? Math.abs(speed) : -Math.abs(speed);
clearInterval(obj.alpha);
obj.alpha = setInterval(function(){
iCur = getStyle( obj, 'opacity' )*100 + speed;
if( (speed > 0 && iCur >= target) || (speed < 0 && iCur <= target) ){
iCur = target;
}
obj.style.opacity = iCur / 100;
obj.style.filter = 'alpha(opacity: '+ iCur +')';
if(iCur == target){
clearInterval(obj.alpha);
if( typeof endFn === 'function' ){ endFn(); }
}
},30);
}
抖动
function shake(obj,attr,endFn){
var pos = getStyle(obj,attr);
var arr = [];
for(var i=14; i>=0; i-=2){
arr.push(-i,i);
}
obj.shake = setInterval(function(){
obj.style[attr] = pos + arr[i++] + 'px';
if(i==arr.length){
clearInterval(obj.shake);
if( typeof endFn === 'function' )endFn();
}
},30);
}
获取计算后的样式
function getStyle( obj ,attr ){
if( obj.currentStyle ){
return parseFloat( obj.currentStyle[attr] || 1 );
}
return parseFloat( getComputedStyle(obj)[attr] );
}
获取计算后的样式并且赋值
function css(obj,attr,val){
if(val){
if(attr=="opacity"){
obj.style['opacity']=val/100;
obj.style['filter']="alpha(opacity="+val+")";
}
else {
obj.style[attr]=val+"px";
}
}
else{
iVal=parseFloat(getStyle(obj,attr));
if(attr=="opacity"){
iVal=Math.round(iVal*100);
}
return iVal;
}
}
DOM下常用封装函数
function getPrev( obj ){
if( !obj || !obj.previousSibling )return null;
return obj.previousSibling.nodeType === 1 ? obj.previousSibling : getPrev( obj.previousSibling );
}
function getNext( obj ){
if( !obj || !obj.nextSibling )return null;
return obj.nextSibling.nodeType === 1 ? obj.nextSibling : getNext( obj.nextSibling );
}
function getFirst( obj ){
if( !obj || !obj.firstChild )return null;
return obj.firstChild.nodeType === 1 ? obj.firstChild : getNext( obj.firstChild );
}
function getLast( obj ){
if( !obj || !obj.lastChild )return null;
return obj.lastChild.nodeType === 1 ? obj.lastChild : getPrev( obj.lastChild );
}
获取元素在当前页面中的绝对位置
function posLeft( obj ){
var iLeft = 0;
while( obj ){
iLeft += obj.offsetLeft;
obj = obj.offsetParent;
}
return iLeft;
}
function posTop( obj ){
var iTop = 0;
while( obj ){
iTop += obj.offsetTop;
obj = obj.offsetParent;
}
return iTop;
}