获取外部 css样式 (计算样式)

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=">
<title>test suit</title>

<script>
function assert(value,desc){
    var li = document.createElement("li");
    li.className = value?"pass":"fail";
    li.appendChild(document.createTextNode(desc));
    document.getElementById("result").appendChild(li);
}

window.onload = function(){
    var div = document.getElementsByTagName("div")[0];
    
    assert(true,"background-color:" + fetchComputedStyle(div,"background-color"));
    assert(true,"display:" + fetchComputedStyle(div,"display"));
    assert(true,"font-size:" + fetchComputedStyle(div,"fontSize"));
    assert(true,"color:" + fetchComputedStyle(div,"color"));
    assert(true,"border-top-color:" + fetchComputedStyle(div,"borderTopColor"));
    assert(true,"border-top-width:" + fetchComputedStyle(div,"border-top-width"));
};

function fetchComputedStyle(element,property){
    if(window.getComputedStyle){
        var computedStyles = window.getComputedStyle(element);                     // 通过window.getComputedStyle(element)获取一个对象接口,在通过给对象的.getPropertyValue(property)来获取相应的属性。
        
        if(computedStyles){
            property = property.replace(/([A-Z])/g,"-$1").toLowerCase();
            return computedStyles.getPropertyValue(property);
        }
    }else if(element.currentStyle){
        property = property.replace(/-([a-z])/ig,function(all,letter){
            return letter.toUpperCase();
        });
    }
    
}

</script>

<style>
    #result li.pass {color : green;}
    #result li.fail {color : red;}
</style>
<style type = "text/css">
    div{
        background-color:#ffc; display:inline; font-size:1.8em;
        border:1px solid crimson; color:green;
    }
</style>
</head>
<body>
    <ul id="result"></ul>
    <div style = "background-color:darkslateblue">$nbsp;</div>
    <div style="background-color:#369">$nbsp;</div>
    <div style="background-color:#123456">$nbsp;</div>
    <div style="background-color:rg6b(44,88,168)">$nbsp;</div>
    <div style="background-color:rgba(44,88,166,0.5)">$nbsp;</div>
    <div style="background-color:hsl(120,100%,25%)">$nbsp;</div>
    <div style="background-color:hsla(120,100%,25%,0.5)">$nbsp;</div>
    <div style = "color:crimson;"  id = "testSubject"  title = "Ninja power!">
        忍者Ninja
    </div>
</body>
</html>

 

posted @ 2017-11-27 15:31  halo-漾  阅读(287)  评论(0编辑  收藏  举报