为什么element.style在JS中总是返回空? [英] Why element.style always return empty in 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不起作用
我的问题不同.
内联样式不是编码的好方法.因此,我们总是在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 thecss
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屋!