<!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>
<title>cssText属性使用</title>
<style type="text/css">
#main{width:100px;height:100px;margin:0px auto;background-color:Black;}
</style>
<script type="text/javascript">
window.onload = function () {
document.getElementById("main").onclick = function () {
//document.getElementById("main").style.cssText = "border:1px solid red;";
document.getElementById("main").style.cssText = "background-color:red;";
}
}
</script>
</head>
<body>
<div id="main"></div>
</body>
</html>
-----------------------------------------------------
一般情况下我们用js设置元素对象的样式会使用这样的形式
var element= document.getElementById("id");
element.style.width="20px";
element.style.height="20px";
element.style.border="solid 1px red";
样式一多,代码就很多;而且通过JS来覆写对象的样式是比较典型的一种销毁原样式并重建的过程,这种销毁和重建,都会增加浏览器的开销。
js中有一个cssText的方法:
语法为:obj.style.cssText="样式";
下面是是正确的
element.style.cssText="width:20px;height:20px;border:solid 1px red;";
这样就可以尽量避免页面reflow,提高页面性能。