style对象的cssText方法有哪些使用方法

  cssText本质是什么?
 
  cssText的本质就是设置HTML元素的style属性值。
 
  cssText怎么用?
 
  domElement.style.cssText="color:red;font-size:13px;";
 
  cssText返回值是什么?
 
  在某些浏览器中(比如Chrome),你给他赋什么值,它就返回什么值。在IE中则比较痛苦,它会格式化输出、会把属性大写、会改变属性顺序、会去掉最后一个分号,比如:
 
  document.getElementById("d1").style.cssText="color:red;font-size:13px;";2alert(document.getElementById("d1").style.cssText);
 
  在IE中值为:FONT-SIZE:13px;COLOR:red
 
  cssText的使用优势
 
  一般情况下我们用js设置元素对象的样式会使用这样的形式:
 
  varelement=document.getElementById(“id”);
 
  element.style.width=”20px”;
 
  element.style.height=”20px”;
 
  element.style.border=”solid1pxred”;
 
  样式一多,代码就很多;而且通过JS来覆写对象的样式是比较典型的一种销毁原样式并重建的过程,这种销毁和重建,都会增加浏览器的开销。
 
  js中有一个cssText的方法:
 
  domElement.style.cssText=”样式”;
 
  domElement.style.cssText=”width:20px;height:20px;border:solid1pxred;”;
 
  这样就可以尽量避免页面reflow,提高页面性能。
 
  但是,这样会有一个问题,会把原有的cssText清掉,比如原来的style中有’display:none;’,那么执行完上面的JS后,display就被删掉了。
 
  为了解决这个问题,可以采用cssText累加的方法:
 
  domElement.style.cssText+=‘;width:100px;height:100px;top:100px;left:100px;’
 
  再进一步,如果前面有样式表文件写着div{text-decoration:underline;},这个会被覆盖吗?不会!因为它不是直接作用于HTML元素的style属性。
 
  具体案例分析:
 
  
 
  
 
  <!DOCTYPEhtmlPUBLIC"-//W3C//DTDXHTML1.0Transitional//EN""http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
  <htmlxmlns="http://www.w3.org/1999/xhtml">
 
  <head>
 
  <metahttp-equiv="Content-Type"content="text/html;charset=utf-8"/>
 
  <title>控制div属性</title>
 
  <style>
 
  #outer{width:500px;margin:0auto;padding:0;text-align:center;}
 
  #div1{width:100px;height:100px;background:black;margin:10pxauto;display:block;}
 
  </style>
 
  <script>
 
  varchangeStyle=function(elem,attr,value)
 
  {
 
  elem.style[attr]=value
 
  };
 
  window.onload=function()
 
  {
 
  varoBtn=document.getElementsByTagName("input");
 
  varoDiv=document.getElementById("div1");
 
  varoAtt=["width","height","background","display","display"];
 
  varoVal=["200px","200px","red","none","block"];
 
  for(vari=0;i<oBtn.length;i++)
 
  {
 
  oBtn[i].index=i;
 
  oBtn[i].onclick=function()
 
  {
 
  this.index==oBtn.length-1&&(oDiv.style.cssText="");
 
  changeStyle(oDiv,oAtt[this.index],oVal[this.index])
 
  }
 
  }
 
  };
 
  </script>
 
  </head>
 
  <body>
 
  <divid="outer">
 
  <inputtype="button"value="变宽"/>
 
  <inputtype="button"value="变高"/>
 
  <inputtype="button"value="变色"/>
 
  <inputtype="button"value="隐藏"/>
 
  <inputtype="button"value="重置"/>
 
  <divid="div1"></div>
 
  </div>
 
  </body>
 
  </html>







Copyright Liukaiweb.Com Rights Reserved.

 渝ICP备2021008408号-5