HTML的样式写入方法有:1、行内样式;2、内嵌样式;3、外联样式表。
- 行内样式:一般是用style写在dom元素上的,例如:<div style='height:200px;'></div>;
- 内嵌样式:一般是用style写在head标签内的。<style type='text/css'></style>;
- 外联样式:一般是用link标签或者是import引入的。但import引入的时候一定要放在style标签内。
获取样式:
一、ele.style
通过这种方式只能获取到写在行内的样式。其他两种是获取不到的。例如:
var con = document.getElementById("con"); con.style.height; //只能获取到写在行内的height值。
二、ele.getComputedStyle (只读)
可以获取到当前元素所使用到额最终的css属性值,返回是一个css样式声明对象。
用法:var style = window.getComputedStyle(dom,[pseudoElt]);
dom 用于获取计算样式的Element pseudoElt 指定一个要匹配的伪元素的字符串。必须对普通元素省略(或null)
例如: <div class="a" style="height: 300px;"></div>
<script type="text/javascript">
var a = document.getElementsByClassName("a")[0];
var con = window.getComputedStyle(a);
console.log(con)
</script>
得到的结果如下:
如果想获取到其中的高度值(height)则可以:var H = window.getComputedStyle(a).height; 这样就可以拿到高度值。
三、ele.currentStyle
在旧版本的IE浏览器想要达到和getComputedStyle的功能。可以使用currentStyle方法
例如:var test = document.getElmentById('test');
console.log(test.currentStyle.color) //可以拿到id为test的元素的字体颜色
四、getPropertyValue获取CSS样式的直接属性名称
用法:
window.getComputedStyle(element, null).getPropertyValue(属性);
例如:var test = document.getElmentById('test');
window.getComputedStyle(test, null).getPropertyValue("background-color");
注意:属性名不支持驼峰格式,IE6-8不支持该方法,需要使用下面的方法
五、getAttribute与getPropertyValue类似,有一点的差异是属性名驼峰格式
例子:
var test = document.getElementById('test');
window.getComputedStyle(test, null).getPropertyValue("backgroundColor");
注意:该方法只支持IE6-8
六、使用jquery.js来获取样式
其实jq获取元素的样式也是对ele.currentStyle和ele.getComputedStyle、getPropertyValue、getAttribute 进行了整体的封装。