前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >获取元素CSS样式

获取元素CSS样式

作者头像
ProsperLee
发布2019-03-06 12:52:54
1.7K0
发布2019-03-06 12:52:54
举报
 1 <!DOCTYPE html>
 2 <html lang="en">
 3 
 4 <head>
 5     <meta charset="UTF-8">
 6     <meta name="viewport" content="width=device-width, initial-scale=1.0">
 7     <meta http-equiv="X-UA-Compatible" content="ie=edge">
 8     <title>获取css样式</title>
 9 </head>
10 <style>
11     #box{
12         position: absolute;
13         left: 50%;
14         top: 100px;
15         background-color: #fff000;
16         color: blueviolet;
17         font-size: 2em;
18         font-weight: bolder;
19         text-align: center;
20         width: 300px;
21         height: 100px;
22         line-height: 100px;
23         font-style: italic;
24     }
25 </style>
26 <body>
27     <div id="box">ProsperLee</div>
28     <pre>
29         #box{
30             position: absolute;
31             left: 50%;
32             top: 100px;
33             background-color: #fff000;
34             color: blueviolet;
35             font-size: 2em;
36             font-weight: bolder;
37             text-align: center;
38             width: 300px;
39             height: 100px;
40             line-height: 100px;
41             font-style: italic;
42         }
43     </pre>
44     <script>
45         /**
46          * 获取css样式
47          * ele 元素
48          * prop 属性名
49          **/
50         function getStyle(ele, prop) {
51             if (window.getComputedStyle) {
52                 return window.getComputedStyle(ele, null)[prop];
53             } else {
54                 return ele.currentStyle[prop];
55             }
56         }
57         var el = document.getElementById('box');
58         console.log('position:' + getStyle(el,'position')); // absolute
59         console.log('left:' + getStyle(el,'left')); // 488.5px
60         console.log('font-size:' + getStyle(el,'font-size')); // 32px
61         console.log('font-style:' + getStyle(el,'font-style')); // italic
62         console.log('max-width:' + getStyle(el,'max-width')); // none
63         console.log('bottom:' + getStyle(el,'bottom')); // 532px
64     </script>
65 </body>
66 
67 </html>
本文参与 腾讯云自媒体分享计划,分享自作者个人站点/博客。
原始发表:2019-02-22 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档