javascript - 为什么 element.style 在 JS 中总是返回空?

标签 javascript html css styles

当您在 css 中定义 display:block 时,element.style.display 总是返回空的。

console.log(document.getElementById('test').style.display)
#map {display: block;}
<div id="test">test</div>

但是如果你在该元素中设置样式,那么我们可以获得样式。显示详细信息。

    console.log(document.getElementById('test').style.display)
 <div style="display:none" id="test">test</div>

我不想要解决方案,因为我知道有很多解决方案:

getElementById().style.display does not work

Show/Hide google maps api does not work fine

我的问题不同。

Inline style is not a good way of coding. So we always assign the style in CSS. But why it's showing empty while provide style property in CSS instead of via the element? Is JavaScript particularly can't read the css style property?

你可以在下面查看,所有样式属性都是空的,即使我提供了 display: block; 对齐内容:居中;为什么?

console.log(document.getElementById('test').style)
#map {display: block;align-content:center;}
<div id="test">test</div>

最佳答案

element.style 返回 html 文档中使用的内联样式,由于样式不是直接在 html 中设置的,您将得到空值

您正在寻找的是 computedStyle,它将返回应用于元素的样式

console.log(window.getComputedStyle(document.getElementById('test')).display)
#map {
      display: block;
      align-content:center;
    }
<div id="test">test</div>

关于javascript - 为什么 element.style 在 JS 中总是返回空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56249283/

相关文章:

javascript - anchor 链接的平滑滚动不起作用

javascript - 移动物体性能 - ThreeJs

Javascript 图像 slider 无法正常工作

html - 悬停时如何将图像放在其父div之外

javascript - iOS PWA 音频限制

jquery - CSS伪类覆盖类

javascript - 需要使用 redux 从数组中删除项目

javascript - 如何使用 Django/Tastypie API 创建 CRUD?

html - 我的 CSS 不起作用,除了我网站中的一页

html - 如何使用 CSS 隐藏某些页面上的 div