javascript 一些关于css操作的函数
// 通过样式表 获得css样式
//obj 表示dom对象,name 表示css属性 比如width等
function getStyle(obj,name){
if(obj.currentStyle){
return obj.currentStyle[name];
}else{
return getComputedStyle(obj,false)[name];
}
}
利用cssText 批量设置元素的属性
obj.style.cssText="width:150px;height:500px;"
和innerHTML一样,cssText很快捷且所有浏览器都支持。此外当批量操作样式时,cssText只需一次reflow,提高了页面渲染性能。
但cssText也有个缺点,会覆盖之前的样式。
但cssText也有个缺点,会覆盖之前的样式。如
<div style="color:red;">TEST</div>
div.style.cssText = "width:200px;";
这时虽然width应用上了,但之前的color被覆盖丢失了。因此使用cssText时应该采用叠加的方式以保留原有的样式。
function setStyle(el, strCss){
var sty = el.style;
sty.cssText = sty.cssText + strCss;
}
使用该方法在IE9/Firefox/Safari/Chrome/Opera中没什么问题,但由于 IE6/7/8中cssText返回值少了分号 会让你失望。
因此对IE6/7/8还需单独处理下,如果cssText返回值没";"则补上
function setStyle(el, strCss){
function endsWith(str, suffix) {
var l = str.length - suffix.length;
return l >= 0 && str.indexOf(suffix, l) == l;
}
var sty = el.style,
cssText = sty.cssText;
if(!endsWith(cssText, ';')){
cssText += ';';
}
sty.cssText = cssText + strCss;
}
通过class 获得元素
//oParent 表示父元素 sclass 表示子元素的class名字
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; }

浙公网安备 33010602011771号