簡體   English   中英

如何檢索 DOM 元素的顯示屬性?

[英]How to retrieve the display property of a DOM element?

<html>
    <style type="text/css">
        a {
            display: none;
        }
    </style>
    <body>
        <p id="p"> a paragraph </p>
        <a href="http://www.google.com" id="a">google</a>
    </body>
    <script type="text/javascript">
        var a = (document.getElementById('a')).style;
        alert(a.display);
        var p = (document.getElementById('p')).style;
        alert(p.display);
        p.display = 'none';
        alert(p.display);
    </script>
</html>

第一個和第二個alert只顯示一個空字符串,我認為它應該是noneblock 但是在 intensally display設置之后,第三個alert終於 alert none了。

但為什么? 如何正確檢索display屬性?

謝謝。

.style.*屬性直接映射到style屬性,而不是應用的樣式。 為此,您需要getComputedStyle

我會認真考慮切換.className並將演示文稿與邏輯完全分開。

您需要元素的顯示屬性的計算值。 你可以得到這個如下。 請注意,大多數瀏覽器都支持window.getComputedStyle()而在 IE 中最接近的等價物是元素的currentStyle屬性:

var el = document.getElementById('a');
var styleObj;

if (typeof window.getComputedStyle != "undefined") {
    styleObj = window.getComputedStyle(el, null);
} else if (el.currentStyle != "undefined") {
    styleObj = el.currentStyle;
}

if (styleObj) {
   alert(styleObj.display);
}

我建議使用 JavaScript 庫來獲取計算樣式。 例如,使用 jQuery,您可以使用 css() 方法檢索計算樣式...

$("#a").css("display");

css() 方法是一種跨瀏覽器解決方案,因為它在內部使用樣式對象以及 getComputedStyle 方法和 currentStyle 對象。

如果你可以使用 jQuery,有一個方法叫做.is

要檢查是否未顯示某些內容,我會這樣做 ... $('someSelector').is(':visible') ...

如果顯示屬性設置為無,這將返回 false。

暫無
暫無

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

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