obj.style方法,這個方法只能JS只能獲取寫在html標籤中的寫在style屬性中的值(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>JS獲取CSS屬性值</title>
- <style type="text/css">
- <!--
- .ss{color:#cdcdcd;}
- -->
- </style>
- </head>
- <body>
- <div id="css88" class="ss" style="width:200px; height:200px; background:#333333">JS獲取CSS屬性值</div>
- <script type="text/javascript">
- alert(document.getElementById("css88").style.width);//200px
- alert(document.getElementById("css88").style.color);//空白
- </script>
- </body>
- </html>
上面這個例子對id爲"css88"的div設置了2種煩事的樣式,包括style和外部樣式class。
從alert出來的信息可以看到,document.getElementById("css88").style方法獲取不到class爲ss的屬性和值。
那麼這麼樣才能獲取到class爲ss的屬性和值呢?
IE中使用的是obj.currentStyle方法,而FF是用的是getComputedStyle 方法。
網上一個比較方法是:
- <!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>S獲取CSS屬性值</title>
- <style type="text/css">
- <!--
- .ss{background:blue; color:#cdcdcd; width:200px}
- -->
- </style>
- </head>
- <body>
- <p id="qq" class="ss" >sdf</p>
- <script type="text/javascript">
- function GetCurrentStyle (obj, prop) {
- if (obj.currentStyle) {
- return obj.currentStyle[prop];
- }
- else if (window.getComputedStyle) {
- propprop = prop.replace (/([A-Z])/g, "-$1");
- propprop = prop.toLowerCase ();
- return document.defaultView.getComputedStyle (obj,null)[prop];
- }
- return null;
- }
- var dd=document.getElementById("qq");
- alert(GetCurrentStyle(dd,"width"));
- </script>
- </body>
- </html>
當然,如果您是引用外部的css文件同樣適用。
另:可以將上面的方法簡化爲