[英]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
只顯示一個空字符串,我認為它應該是none
和block
。 但是在 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.