Javascript获取CSS属性值getComputedStyle和currentStyle

使用Javascript获取元素CSS属性值

对于元素的内联CSS样式(<div style="color:#369">hello</div>),可以直接使用element.style.color来直接获取css属性的值,但是对于外部定义的css样式使用这种方式就无法获取了,而且IE浏览器和其他标准浏览器(Firefox,Chrome,Opera,Safari)使用的方法不一样,IE浏览器使用element.currentStyle,W3C标准浏览器使用getComputedStyle来获取。

IE获取元素外部定义的CSS属性值:

element.currentStyle

currentStyle对象返回了元素上的样式表,但是style对象只返回通过style标签属性应用到元素的内嵌样式。因此,通过currentStyle对象获取的样式值可能与通过style对象获取的样式值不同。例如,如果段落的color属性值通过链接或嵌入样式表设置为红色( red ),而不是内嵌的话,对象.currentStyle.color 将返回正确的颜色,而对象style.color不能返回值。但是,如果用户指定了 <P STYLE="color:’red’">,currentStyleSTYLE对象都将返回值 red。
currentStyle对象反映了样式表中的样式优先顺序。在 HTML 中此顺序为:

1) 内嵌样式

2) 样式表规则

3) HTML 标签属性

4) HTML 标签的内部定义

W3C获取元素外部定义的CSS属性值:
window.getComputedStyle(element, pseudoElt)
element必选,HTML元素
pseudoElt必选,获取该元素的伪类样式

 

代码:
<style type="text/css">
.divtitle { background: blue; color: #cdcdcd; width: 200px; }
</style>

<div id="qq" class="divtitle">测试样式</div>
<script type="text/javascript">
        function GetCurrentStyle(obj, prop) {
                if (obj.currentStyle) { //IE浏览器
                        return obj.currentStyle[prop];
                } else if (window.getComputedStyle) { //W3C标准浏览器
                        propprop = prop.replace(/([A-Z])/g, "-$1");
                        propprop = prop.toLowerCase();
                        return document.defaultView.getComputedStyle(obj, null)[propprop];
                }
                return null;
        }
        var dd = document.getElementById("qq");
        alert(GetCurrentStyle(dd, "color"));
</script>

转载于:https://www.cnblogs.com/wcp-spring/archive/2012/09/21/2696651.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值