在学习js初期,就一直有一个疑问,获取元素样式的值,不是直接使用obj.style.left
之类的就可以得到了吗?可是使用这样的方式,有的时候能够获取得到,有的时候又不能获取,一直疑惑不已,但是由于以前学习态度的问题,也没有深究,今天专门花了点时间整理了一下这方面的知识。
样式
首先,我们要明确样式的种类有以下三种
- 内联样式: 也就是行内样式,直接写在DOM元素的style属性中
- 嵌入样式: 写在html页面中的<style></style>中的样式
- 外部样式: 由link标签引入的css文件中的样式
优先级:内联 > 嵌入 > 外部
首先,先写一个例子来测试一下通过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; }
// javascriptvar 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
或者document.defaultView.getComputedStyle( obj, false )
的方式,其中前者适用于IE,后者适用于chrome和Firefox
因此我们可以写一个获取元素样式值的方法
var getStyle = function(obj, key) { ???return obj.currentStyle ? obj.currentStyle[key] : document.defaultView.getComputedStyle( obj, false )[key];}
原生js获取元素样式值
原文地址:http://www.cnblogs.com/chenmingchao/p/7427304.html