首页 > 开发 > CSS > 正文

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

2020-03-24 18:22:42
字体:
来源:转载
供稿:网友
这次给大家带来style对象的cssText方法有哪些使用方法,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; 2 alert(document.getElementById( d1 ).style.cssText);

在 IE 中值为:FONT-SIZE: 13px; COLOR: red

cssText的使用优势

一般情况下我们用js设置元素对象的样式会使用这样的形式:

 var element= document.getElementById(“id”); element.style.width=”20px”; element.style.height=”20px”; element.style.border=”solid 1px red”;

样式一多,代码就很多;而且通过JS来覆写对象的样式是比较典型的一种销毁原样式并重建的过程,这种销毁和重建,都会增加浏览器的开销。

js中有一个cssText的方法:

 domElement.style.cssText=”样式”; domElement.style.cssText=”width:20px;height:20px;border:solid 1px red;”;

这样就可以尽量避免页面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 属性。

具体案例分析:

 !DOCTYPE html PUBLIC -//W3C//DTD XHTML 1.0 Transitional//EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd  html xmlns= http://www.w3.org/1999/xhtml  head  meta http-equiv= Content-Type content= text/html; charset=utf-8 /  title 控制div属性 /title  style #outer{width:500px;margin:0 auto;padding:0;text-align:center;}#div1{width:100px;height:100px;background:black;margin:10px auto;display:block;} /style  script var changeStyle = function (elem, attr, value) elem.style[attr] = valuewindow.onload = function () var oBtn = document.getElementsByTagName( input  var oDiv = document.getElementById( div1  var oAtt = [ width , height , background , display , display  var oVal = [ 200px , 200px , red , none , block  for (var i = 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  div id= outer  input type= button value= 变宽 /  input type= button value= 变高 /  input type= button value= 变色 /  input type= button value= 隐藏 /  input type= button value= 重置 /  div id= div1 /div  /div  /body  /html 

相信看了这些案例你已经掌握了方法,更多精彩请关注php 其它相关文章!

相关阅读:

html与xhtml和xml有什么区别

iframe的子页面怎样操作父页屏蔽页面弹出层效果

以上就是style对象的cssText方法有哪些使用方法的详细内容,html教程

郑重声明:本文版权归原作者所有,转载文章仅为传播更多信息之目的,如作者信息标记有误,请第一时间联系我们修改或删除,多谢。

发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表