js中style,currentStyle和getComputedStyle的区别
2016-06-22 22:05
591 查看
style只能获取元素的内联样式,内部样式和外部样式使用style是获取不到的,style可以对样式进行修改,而currentStyle和getComputedStyle只能读取不能修改。
currentStyle可以弥补style的不足,但是只适用于IE。
getComputedStyle同currentStyle作用相同,但是适用于FF、opera、safari、chrome。
1. obj.style:这个方法只能JS只能获取写在html标签中的写在style属性中的值(style=”…”),而无法获取定义在<style type="text/css">里面的属性。
“DOM2级样式”增强了document.defaultView,提供了getComputedStyle()方法。这个方法接受两个参数:要取得计算样式的元素和一个伪元素字符串(例如“:after”)。如果不需要伪元素信息,第二个参数可以是null。getComputerStyle()方法返回一个CSSStyleDeclaration对象,其中包含当前元素的所有计算的样式。以下面的HTML页面为例:
参考:http://www.jb51.net/article/49278.htm
http://blog.sina.com.cn/s/blog_ae7b1a4001019pc4.html
currentStyle可以弥补style的不足,但是只适用于IE。
getComputedStyle同currentStyle作用相同,但是适用于FF、opera、safari、chrome。
1. obj.style:这个方法只能JS只能获取写在html标签中的写在style属性中的值(style=”…”),而无法获取定义在<style type="text/css">里面的属性。
<style type=”text/css”> <!– .ss{color:#cdcdcd;} –> </style> </head> <body> <div id=”css88″ class=”ss” style=”width:200px; height:200px; background:#333333″>JS获取CSS属性值</div> <script type=”text/javascript”> alert(document.getElementById(“css88″).style.width);//200px alert(document.getElementById(“css88″).style.color);//空白 </script> </body> </html> </span>2. IE中使用的是obj.currentStyle方法,而FireFox是用的是getComputedStyle 方法
“DOM2级样式”增强了document.defaultView,提供了getComputedStyle()方法。这个方法接受两个参数:要取得计算样式的元素和一个伪元素字符串(例如“:after”)。如果不需要伪元素信息,第二个参数可以是null。getComputerStyle()方法返回一个CSSStyleDeclaration对象,其中包含当前元素的所有计算的样式。以下面的HTML页面为例:
<!DOCTYPE html> <html> <head> <title>计算元素样式</title> <style> #myDiv { background-color:blue; width:100px; height:200px; } </style> <body> <div id ="myDiv" style="background-color:red; border:1px solid black"></div> <script> var myDiv = document.getElementById("myDiv"); var computedStyle = document.defaultView.getComputedStyle(myDiv, null); alert(computedStyle.backgroundColor); //"red" alert(computedStyle.width); //"100px" alert(computedStyle.height); //"200px" alert(computedStyle.border); //在某些浏览器中是“1px solid black” </script> </body> </head> </html></span>IE不支持getComputedStyle()方法,但它有一种类似的概念。在IE中,每个具有style属性的元素还有一个currentStyle属性。这个属性是CSSStyleDeclaration的实例,包含当前元素全部计算后的样式。取得这些样式的方法差不多,如下:
var myDiv = document.getElementById("myDiv"); var computedStyle = myDiv.currentStyle; alert(computedStyle.backgroundColor); //"red" alert(computedStyle.width); //"100px" alert(computedStyle.height); //"200px" alert(computedStyle.border); //undefined</span>
参考:http://www.jb51.net/article/49278.htm
http://blog.sina.com.cn/s/blog_ae7b1a4001019pc4.html
相关文章推荐
- JavaScript函数(三)
- Javascript 排序数组或对象
- arcgis api for js共享干货系列之一自写算法实现地图量算工具
- JSP 三个指令七个动作九个对象
- js学习笔记]PDF.js专题
- JavaScript函数(二)
- JSON
- javaScript设计模式之模板方法模式
- 人民币大写在线转换工具
- JavaScript设计模式
- JavaScript对象的扁平化与反扁平化
- JQ JSON数据类型
- JavaScript函数(一)
- 什么是原生的javascript
- JavaScript跨域总结与解决办法
- JavaScript语法详解(四)
- JavaScript语法详解(三)
- JSON导入jar问题
- django中两张表有外键关系的相互查找方法,自定义json编码方法
- JavaScript语法详解(二)