在js中更换样式比较常见,但是批量设置比较少遇见;
但是在做就是插件时,不想额外的添加css文件(需要导入,还可能引起冲突),能批量设置就比较方便了。
以下代码是来自网上的三种方法,使用第二种最方便了。
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>无标题文档</title>
<style type="text/css">
#div1{ width:100px; height:100px; background:#069;}
</style>
<script type="text/javascript">
//第一种使用JSON
function setStyle(obj,json){
for(var i in json)
{
obj.style[i]=json[i];
}
}
window.onload=function(){
var oDiv=document.getElementById('div1');
// setStyle(oDiv, {width: '200px', background: 'red'}); //第一种
// oDiv.style.cssText="width: 200px; height:300px; background:yellow;"; //第二种 使用cssText //使用第三种 with (不推荐使用)
with(oDiv.style)
{
width='300px';
height='500px';
background='yellow';
} };
</script>
</head> <body>
<div id="div1"></div>
</body>
</html>
对于第三种为啥不使用width,是因为它有存在兼容性的问题。
详解请看http://blog.sina.com.cn/s/blog_9c581bd30101adnh.html
赋值:选用“带数值和单位”的写法,如:id.style.width = "100px";
取值:var w = parseInt(id.style.width)