可能是一个重复的问题,但找不到答案。
element.style.display 不是在浏览器中呈现的内容。
它不返回实际值(即 block 或内联等),而是返回空值。在 Chrome 56.0.2924.87(64 位)中测试。
如何获取实际呈现的值?
function displayStyle(aEvent) {
aEvent.target.textContent=aEvent.target.style.display;
}
window.onload = function() {
var top_array = document.getElementsByClassName("top");
for(var i = 0; i < top_array.length; i++)
{
top_array[i].addEventListener("click", displayStyle, false);
}
}
.top{
background-color:#FFF8DC;
}
<div class="top">top (click it and it will disappear because its style.display is empty)</div>
最佳答案
CSS 样式对 JavaScript 不可用,除非它们之前已在 JavaScript 中设置或已被硬编码为内联样式。
使用 getComputedStyle() 改为:
function displayStyle(aEvent) {
var target = aEvent.target;
target.textContent = window.getComputedStyle(target).getPropertyValue('display');
}
window.onload = function() {
var top_array = document.getElementsByClassName("top");
for (var i = 0; i < top_array.length; i++) {
top_array[i].addEventListener("click", displayStyle, false);
}
}
.top {
background-color: #FFF8DC;
}
<div class="top">top (click it and it will now show "block" since we're getting its computed style.)</div>
关于javascript - element.style.display 不是在浏览器中呈现的内容,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43124847/