首页 > 其他 > 详细

获取样式

时间:2016-03-12 21:05:41      阅读:198      评论:0      收藏:0      [点我收藏+]
 1 // JavaScript Document
 2 
 3 function $( v ){
 4     if( typeof v === function ){
 5         window.onload = v;
 6     } else if ( typeof v === string ) {
 7         return document.getElementById(v);
 8     } else if ( typeof v === object ) {
 9         return v;
10     }
11 }
12 
13 function getStyle( obj, attr ){
14     return obj.currentStyle ? obj.currentStyle[attr] : getComputedStyle( obj )[attr];
15 }

 

 

 1 <!DOCTYPE HTML>
 2 <html>
 3 <head>
 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8">
 5 <title>无标题文档</title>
 6 <style>
 7 div { width:100px; height:120px; background:red; }
 8 </style>
 9 <script src="miaov.js"></script>
10 <script>
11 $(function(){
12     
13     // $(‘div1‘).style.width = ‘300px‘;
14     
15     
16     $(btn1).onclick = function  (){
17         // alert( $(‘div1‘).style.width );
18         // $(‘div1‘).style.cssText = ‘width:350px;‘;
19         
20         // alert( getComputedStyle( $(‘div1‘) ).width );            // IE6 7 8 不兼容
21         
22         // alert( $(‘div1‘).currentStyle.width );                                        // 标准浏览器不兼容
23         /*
24         if( $(‘div1‘).currentStyle ){
25             alert( $(‘div1‘).currentStyle.width );
26         } else {
27             alert( getComputedStyle( $(‘div1‘), 250 ).width );
28             // FF 4.0 之前
29         }
30         */
31         
32         // alert( getStyle( $(‘div1‘), ‘width‘ ) );
33         // alert( getStyle( $(‘div1‘), ‘height‘ ) );
34         
35         alert( getStyle( $(div1), marginRight ) );
36         
37         /*
38                 获取到的是计算机(浏览器)计算后的样式
39                 
40                 background: url() red ……        复合样式(不要获取)
41                 backgroundColor                                    单一样式(不要用来做判断)
42                 
43                 不要有空格
44                 
45                 不要获取未设置后的样式:不兼容
46         */
47     };
48 });
49 
50 
51 </script>
52 </head>
53 
54 <body>
55 
56 <input id="btn1" type="button" value="按钮" />
57 <div id="div1"></div>
58 
59 </body>
60 </html>

 

获取样式

原文:http://www.cnblogs.com/hduhdc/p/5270039.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!