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/p/1979583.html