在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)