在学习 js 初期,就一直有一个疑问,获取元素样式的值,不是直接使用
之类的就可以得到了吗?可是使用这样的方式,有的时候能够获取得到,有的时候又不能获取,一直疑惑不已,但是由于以前学习态度的问题,也没有深究,今天专门花了点时间整理了一下这方面的知识。
- obj.style.left
首先,我们要明确样式的种类有以下三种
首先,先写一个例子来测试一下通过 style 方法获取元素样式的值,思路是,一个样式写在行内,一个样式写在 style 标签中,一个样式由 link 引入
- <head>
- <meta charset="UTF-8">
- <title>
- get style
- </title>
- <style>
- <!-- 嵌入样式 -->
- .box { height: 200px; }
- </style>
- <!-- 引入外部样式 -->
- <link rel="stylesheet" href="./index.css">
- </head>
- <body>
- <!-- 行内样式 -->
- <div class="box" style="width: 100px;">
- </div>
- </body>
- // index.css
- .box { background-color: orange; }
- // javascript
- var box = document.getElementsByClassName('box')[0];
- console.log(box.style.width);
- console.log(box.style.height);
- console.log(box.style.backgroundColor);
得到的结果为:
- '100px'
- ''
- ''
因此我们可以看到 height 值和 backgroundColor 值没有被获取到,所以我们得到以下结论:
style 只能获取行内样式的值,无法获取嵌入式样式和外部样式的值
那么嵌入式样式和外部样式的值应该怎么办呢,看下面代码
- // currentStyle: IE下获取元素样式的值
- if (box.currentStyle) {
- console.log('this is IE.');
- console.log(box.currentStyle.width);
- console.log(box.currentStyle.height);
- console.log(box.currentStyle.backgroundColor);
- } else {
- // chorme and firefox
- console.log(document.defaultView.getComputedStyle(box, false).width);
- console.log(document.defaultView.getComputedStyle(box, fasle).height);
- console.log(document.defaultView.getComputedStyle(box, false).backgroundColor);
- }
输出结果
- 'this is IE.'
- '100px'
- '200px'
- 'orange'
分别在 IE, chrome, firefox 下测试一下,最后都能够获取所有的属性。非常好,于是我们可以得出结论
获取元素样式值的最佳方式,就是通过
或者
- obj.currentStyle
的方式,其中前者适用于 IE,后者适用于 chrome 和 Firefox
- document.defaultView.getComputedStyle( obj, false )
因此我们可以写一个获取元素样式值的方法
- var getStyle = function(obj, key) {
- return obj.currentStyle ? obj.currentStyle[key] : document.defaultView.getComputedStyle(obj, false)[key];
- }
来源: http://www.bubuko.com/infodetail-2277998.html