style的属性 样式设置 兼容各浏览器(还有待改进)

window.onload = function(){
 setStyle(document.getElementById('box'),"color:#336699;font-weight:bold");
};

//可以传字符串,也可以传对象格式:{color:"#FF0000",fontWeight:"bold"}

//请注意连接样式的写法fontWeight不能写成font-weight或者font-Weight
function setStyle(currNode, oStyle){
   var cssText = currNode.getAttribute("style"); //Get the old style
   if(cssText === null) cssText = "";
   else if(cssText.lastIndexOf(";")+1 !== cssText.length){ //IE have not the ';' end of the cssText
     cssText += ";";
   }
  
   if(typeof oStyle == "object") {
      //oStyle.setAttribute("cssText", strStyle);这种应该是为了兼容IE低版本的,没有测过
  for(var i in oStyle){
        cssText += i.replace(/([A-Z])/,"-$1").toLowerCase() + ":"+ oStyle[i] + ";"; //for the font-weight、boder-bottom edc.
  }

 currNode.setAttribute("cssText", cssText);
  currNode.setAttribute("style",cssText);
   }else {

      currNode.setAttribute("cssText", cssText+oStyle);
      currNode.setAttribute("style", cssText + oStyle);
   }
}

注://oStyle.setAttribute("cssText", strStyle);这种应该是为了兼容IE低版本的,没有测过。如果发现有浏览器不兼容,优先注意此设置。~>_<~

还有一个问题就是设置的样式属性可能会重复,如:行内样式中已经定义font-size:12px ,而经此方法后,会再增加一个font-size:14px;变成

font-size:12px;font-size:14px;很明显前一个变得多余了,虽然不会影响到最终我们想要的效果,但可能会留下些后遗症。

改进起来,还要花些时间,有时间再来改了。

转载于:https://www.cnblogs.com/Denny_Yang/archive/2011/03/10/1979583.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值