簡體   English   中英

JavaScript警報getElementsByClassName(“ x”)。style.display

[英]Javascript alert getElementsByClassName(“x”).style.display

我試圖通過按類排序的JS獲取“顯示”的值。 我的代碼是:

var x = document.getElementsByClassName("codeContainer");
alert(x[0].style.display);

問題是警報框只是空的。 通話

alert(x.length);

效果很好,返回“ 4”。 我究竟做錯了什么? 非常感謝!

問題是,如果元素是使用外部CSS而不是使用樣式屬性使用內聯CSS設置格式的,則勢必會獲得空白值。

alert(x[0].style.display);

使用內聯CSS:

 var inputs = document.getElementsByTagName('input'); console.log('total inputs:', inputs.length); var bg = inputs[0].style.background; console.log('background:', bg); 
 <input type='text' style='background:orange' /> 

您需要獲取相同的getStyle()reference的計算樣式。

 var getStyle = function(el, cssprop) { if (el.currentStyle) //IE return el.currentStyle[cssprop] else if (document.defaultView && document.defaultView.getComputedStyle) //Firefox return document.defaultView.getComputedStyle(el, "")[cssprop] else //try and get inline style return el.style[cssprop] } var inputs = document.getElementsByTagName('input'); console.log('total inputs:', inputs.length); console.log('color:', getStyle(inputs[0], 'color')); 
 .input { color: blue; } 
 <input type='text' class='input' value='hi' /> <input type='text' class='input' value='hello' /> 

未定義屬性“ style.display”。 因此它返回“空”

您可以嘗試以下方法:

alert(x[0].style.display||window.getComputedStyle(x[0],null).getPropertyValue("display"));

在DOM准備好之后,我們才應該檢查屬性。 請檢查下面的代碼。

(function(){var x = document.getElementsByClassName("codeContainer");

alert(x[0].style.display);})();

暫無
暫無

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

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