js猎取元素款式

内联款式:

Element.style

外部款式:

1.getComputedStyle():能够猎取当前元素终究运用的css属性值

 window.getComputedStyle("元素", "伪类/null").attribute;
document.defaultView.getComputedStyle("元素", "伪类");

注重:Firefox和Safari会将色彩转换成rgb花样

2.element.currentStyle—–ie浏览器
返回的是元素当前运用的终究CSS属性值(包含外链CSS文件,页面中嵌入的<style>属性等)

element.currentStyle.attribute

3.getPropertyValue():猎取css款式直接属性称号

window.getComputedStyle(element, null).getPropertyValue(属性);  

var test = document.getElementById('test');
window.getComputedStyle(test, null).getPropertyValue("background-color");

4.getAttribute

var test = document.getElementById('test');
window.getComputedStyle(test, null).getPropertyValue("backgroundColor");

兼容性处理体式格局:

Function getStyle(obj, attr){
    if(obj.currentStyle){
        return obj.currentStyle;
    }else{
        return getComputedStyle(obj,null); 
    }
}
    原文作者:ciyel
    原文地址: https://segmentfault.com/a/1190000009073636
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞