为什么element.style在JS中总是返回空? [英] Why element.style always return empty in JS?

查看:167
本文介绍了为什么element.style在JS中总是返回空?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在CSS中定义display:block时,element.style.display始终返回空.

When you define display:block in css, element.style.display is returning always empty.

console.log(document.getElementById('test').style.display)

#map {display: block;}

<div id="test">test</div>

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

But if you set style in that element, then we can get the style.display details.

    console.log(document.getElementById('test').style.display)

 <div style="display:none" id="test">test</div>

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

I don't want the solutions because I know SO having lot of solutions for it :

getElementById().style.display不起作用

显示/隐藏google maps api不能正常工作

我的问题不同.

内联样式不是编码的好方法.因此,我们总是在CSS中分配样式.但是,为什么在CSS中提供样式属性而不是通过element时却显示为空? JavaScript是否特别无法读取css样式属性?

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; align-content:center;,所有样式属性都为空. 为什么?

you can check below, all the style properties are empty even I am providing display: block; align-content:center;. Why?

console.log(document.getElementById('test').style)

#map {display: block;align-content:center;}

<div id="test">test</div>

推荐答案

element.style返回html文档中使用的内联样式,由于该样式未直接在html中设置,因此您将获得并为空值

element.style returns the inline style used in html document and since the style is not set directly in html you will get and empty value

您要查找的是computeedStyle,它将返回应用于元素的样式

What you are looking for is the computedStyle which will returns the style that is applied to the element

console.log(window.getComputedStyle(document.getElementById('test')).display)

#map {
      display: block;
      align-content:center;
    }

<div id="test">test</div>

这篇关于为什么element.style在JS中总是返回空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆