为什么getComputedStyle在元素创建后立即返回像素值的“auto”? [英] Why does getComputedStyle return 'auto' for pixels values right after element creation?
问题描述
我使用Mustache来生成一些HTML,并使用 insertAdjacentHTML
将它放在页面上。它显然转换为DOM结构,因为我可以通过使用 document.querySelector('。contentarea')
调用获得一个句柄。但是,如果我尝试获取宽度或高度的像素值,它会不断地返回'auto'
。
I used Mustache to generate some HTML and used insertAdjacentHTML
to place it on the page. It apparently converted to a DOM structure alright since I can get a handle to it afterwards by using a document.querySelector('.contentarea')
call. However, if I try to get a pixel value for width or height, it keeps throwing back 'auto'
.
认为它可能只是一个问题与 getComputedStyle
,我尝试使用 .getBoundingClientRect
和。 offsetWidth
。两者返回 0
。如果我通过将它放在 setTimeout(function(){},1)
中稍微延迟调用,但是这对我的生产代码不实用,因为它需要去
Thinking it might just be a problem with getComputedStyle
, I tried using .getBoundingClientRect
and .offsetWidth
instead. Both returned 0
. It works if I delay the call slightly by placing it inside a setTimeout(function(){}, 1)
, but that's not practical for my production code since it needs to go inside a synchronous constructor.
这是发生在Firefox(Aurora)和Chrome。
我记得阅读一篇关于Mozilla如何通过使用延迟框架构造改善DOM操作性能的文章,并认为可能有一个框架有点小错误懒惰,但由于它发生在Chrome
This is happening in both Firefox (Aurora), and Chrome. I remembered reading an article on how Mozilla improved DOM manipulation performance by using lazy frame construction and thought there might be a bug with the frames being a little too lazy, but since it's happening in Chrome as well, that seems less likely.
有没有人对这里发生了什么或如何解决它有任何想法?在插入HTML之后,我真的需要像素高度/宽度信息。
Does anyone have any ideas about what's going on here or how to work around it? I really need the pixel height/width information immediately after inserting the HTML.
PS:任何浏览器在单独的线程中做HTML到DOM解析/构建吗?我认为这可能会导致这种行为。
PS: Do any browsers do the HTML to DOM parsing/building in a separate thread? I was thinking that might cause this sort of behavior as well.
NEVERMIND:这是我自己的错。我只是没有注意到在代码尝试获取测量之前设置的 display:none;
样式。
NEVERMIND: It was my own fault. I just didn't notice a display: none;
style that was set before the code tried to get the measurements.
推荐答案
有几个事情可以导致auto的结果。你找到了一个; display:none
。如果元素是内联的,它也将返回auto。
There are a couple of things that can cause a result of "auto". You found one of them; display: none
. If an element is inline it will also return auto.
基本上它必须是块
或 inline-block
元素,它必须被渲染。
Essentially it must be a block
or inline-block
element and it must be rendered.
这篇关于为什么getComputedStyle在元素创建后立即返回像素值的“auto”?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!