簡體   English   中英

document.style.getPropertyValue與document.defaultView.ComputedStyles

[英]document.style.getPropertyValue vs document.defaultView.ComputedStyles

我正在閱讀一本高級JavaScript書,他們在其中詳細介紹了DOM 2中添加的樣式對象及其新屬性。為理解這一概念,我編寫了一個小型比較程序,以查看getPropertyValue和ComputedStyles值的行為。 這是下面的程序

<!DOCTYPE html>
<html>
    <head>
        <title>Style comparison</title>
        <style type="text/css">
            #myDiv2
            {
                background-color: brown;
                height: 200px;
            }
        </style>
    </head>
    <body>
        <h1>Comparison</h1>
        <div>
            <h2>Using getPropertyValue function - style object</h2>
            <div id="myDiv" style="background-color: blue; width:100px; border: 1px solid black"></div>
            <input type="button" value="Get property Value on inline style" onclick="getPropertyValue()">
        </div>
        <div>
            <h2>Using documentView.getComputedStyles - DOM 2 methods</h2>
            <div id="myDiv2"></div>
            <input type="button" value="getComputedStyles" onclick="getComputedStyles()">
        </div>
        <script type="text/javascript">
            function getPropertyValue() {

                var div = document.getElementById("myDiv");

                var properties = new Array();

                for(var i = 0, len = div.style.length; i < len; i++) {

                    var propertyName = div.style[i];
                    var value = div.style.getPropertyValue(propertyName);

                    properties.push(propertyName + " " + value);
                }

                alert(properties.join("\n"));
            }

            function getComputedStyles() {

                var div = document.getElementById("myDiv2");

                var computedStyles = document.defaultView.getComputedStyle(div, null);

                alert(computedStyles.backgroundColor);
                alert(computedStyles.height);

                /*for(var i=0, len=computedStyles.length; i<len; i++){

                    alert(computedStyles[i]);
                }*/
            }
        </script>
    </body>
</html>

因此,基於此,我確實理解我們getPropertyValue聯樣式CSS上使用getPropertyValue來訪問屬性名稱和值。 但是, getComputedStyle返回<style>或外部樣式表中的屬性值。 我現在的問題是如何使用getComputedStyles訪問屬性名稱和值,例如可以使用getPropertyValue訪問的屬性名稱和值?

編輯:為了更好地改寫我的問題。 因此,使用var computeStyles = document.defaultView.getComputedStyles(“ myDiv2”,null),我可以像這種computeStyles.backgroundColor一樣訪問background-color的屬性值。 但是,如何訪問屬性名稱本身? 希望清楚。 謝謝

您已經接近答案了...

window.getComputedStyle(div, null).getPropertyValue("background-color");

要么

document.defaultView.getComputedStyle(div, null).getPropertyValue("background-color")

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM