style对象的cssText方法
cssText 本質是什么?
cssText 的本質就是設置 HTML 元素的 style 屬性值。
cssText 怎么用?
domElement.style.cssText = "color:red; font-size:13px;";cssText 返回值是什么?
在某些瀏覽器中(比如 Chrome),你給他賦什么值,它就返回什么值。在 IE 中則比較痛苦,它會格式化輸出、會把屬性大寫、會改變屬性順序、會去掉最后一個分號,比如:
1 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累加的方法:
再進一步,如果前面有樣式表文件寫著 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] = value }; window.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>?本文是在學習了https://www.cnblogs.com/majingyi/p/6840818.html的基礎上修改轉載的。
總結
以上是生活随笔為你收集整理的style对象的cssText方法的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 关于盒模型的一点总结
- 下一篇: 移动端 fixed 固定按钮在屏幕下方,