一.兼容地获取非行间样式(兼容火狐,ie,chrome)
function getStyle(obj,name) { if(obj.currentStyle){ return obj.currentStyle[name]; }else{ return getComputedStyle(obj,false)[name]; } } //调用 window.onload=function () { var oDiv=document.getElementById('div1'); alert(getStyle(oDiv,'width')); };
说明:只能获取单一样式,不能获取复合样式。
单一样式:width、height、position
复合样式:background、border。例如,如果想取背景颜色,可以用backgroundColor
二.封装getByClass
function getByClass(oParent,sClass){ var aEle=oParent.getElementsByTagName('*'); var aResult=[]; for(var i=0;i<aEle.length;i++){ if(aEle[i].className==sClass){ aResult.push(aEle[i]); } } return aResult; }
三.比较完美的运动框架
1.支持多物体,对任意属性值,链式运动,以及多个值同时运动的情况,满足80%的运动情况。
调用:startMove(obj,json,fnEnd)。第一个参数是运动的物体。中间一个参数是传一个包含希望运动的属性的json,例如想要同时变高和宽和透明度,可以var json={'height':300,'width':300,'opacity':100};,最后一个参数是传一个函数,即执行完该运动后,想要接着执行的运动。
2.代码:
// JavaScript Document window.onload=function (){ var oDiv1=document.getElementById('div1'); oDiv1.onmouseover=function (){ startMove(this,'opacity',100); }; oDiv1.onmouseout=function (){ startMove(this,'opacity',30); }; }; function getStyle(obj,name){ if(obj.currentStyle){ return obj.currentStyle[name]; }else{ return getComputedStyle(obj,false)[name]; } } //例如startMove(oDiv,{width:400,height:400}) function startMove(obj,json,fnEnd){ clearInterval(obj.timer); obj.timer=setInterval(function (){ var bStop=true; //假设所有的值都已经到了 for(var attr in json){ var cur=0; if(attr=='opacity'){ cur=Math.round(100*parseFloat(getStyle(obj,attr))); }else{ cur=parseInt(getStyle(obj,attr)); } var speed=(json[attr]-cur)/6; speed=speed>0?Math.ceil(speed):Math.floor(speed); if(cur!=json[attr]) bStop=false; if(attr=='opacity'){ obj.style.filter='alpha(opacity:'+(cur+speed)+')'; obj.style.opacity=(cur+speed)/100; }else{ obj.style[attr]=cur+speed+'px'; } } if(bStop){ clearInterval(obj.timer); if(fnEnd) fnEnd(); } },30); }