1 一般给元素设置行内样式,如<div id="div1" style="width:500px;"></div>。如要获取它的样式,即可document.getElementById("div1").style.width来获取或设置。但是如果样式是在外链link中的或者是页面的非行内样式,就获取不到了。
2
3 在标准浏览器中可以通过window.getComputedStyll(obj,null)[property]来获取外链样式,但是在ie浏览器中则是通过obj.currentStyle来获取。
4
5 完整html代码:
6 <!DOCTYPE html>
7 <html>
8 <head>
9 <title>js获取元素的外链样式-柯乐义</title><base target="_blank"/>
10 <style type="text/css">
11 p {
12 width: 500px;
13 line-height: 30px;
14 }
15 </style>
16 <script src="http://keleyi.com/keleyi/pmedia/jquery/jquery-1.11.2.min.js">
17 </script>
18 <script>
19 function getstyle(obj,property){
20 if(obj.currentStyle){
21 return obj.currentStyle[property];
22 }else if(window.getComputedStyle){
23 return document.defaultView.getComputedStyle(obj,null)[property];//或者也可以通过window.getComputedStyle来获取样式
24 }
25 return null;
26 }
27
28 $(document).ready(function(){
29 $("p").click(function(){
30 alert(getstyle(this,"width"));
31 });
32 });
33 </script>
34
35 </head>
36 <body>
37 <p style="width:750px;">如果您点击我,弹出宽度。</p>
38 <p>点击我,弹出宽度。</p>
39 <p>也要点击我哦。</p>
40 <div><a href="http://keleyi.com">首页</a> <a href="http://keleyi.com/keleyi/phtml/">特效库</a> <a href="http://keleyi.com/a/bjae/nb9lb3sd.htm">原文</a></div>
41 </body>
42 </html>
43
44 本文转载自柯乐义http://keleyi.com/a/bjae/nb9lb3sd.htm