DOM 刷新后使用 jQuery 测量宽度()
我的脚本在内部动态创建一个
:它是一个分页器。然后,脚本测量所有
- 的宽度并对它们求和。
宽度左浮动
问题是,在将节点注入到文档中之后,浏览器刷新 DOM 并应用 CSS 样式,这需要一段时间。它对我的脚本产生负面影响:当这些操作在我测量宽度之前未完成时,我的脚本会得到错误的值。如果我在一秒钟内完成测量——一切都会好起来的。
我正在寻找的是一种检测
完全绘制、应用样式且宽度稳定的时刻的方法。或者至少有一种检测每个维度变化的方法。当然,我可以使用 setTimeout(..., 100)
但它很丑陋,我想 - 根本不是一个解决方案。如果有一种方法可以检测宽度稳定性——我会在它之后立即进行测量以获得正确的值。
由 DOM 生成的 HTML 代码
<div>
<ul>
<li><a href="...">1</a></li>
<li><a href="...">2</a></li>
....
</ul>
</div>
PS 为什么我需要这个。 我的分页器的左浮动
项目往往会移动到下一行当
是不可见的:
试图变得比页面本身更宽时。尽管由于父
的宽度限制,大多数
div { width: 500px; overflow: hidden; }
div ul { width: 100%; white-space: nowrap; }
div ul li { display: block; float: left; }
除非我指定了实际的总宽度,否则它们仍然会下降。
与脚本。My script dynamically creates a <ul>
width left-floating <li>
s inside: it's a paginator. Afterwards, the script measures width of all <li>
s and summs them up.
The problem is that after the nodes are injected into the document — the browser refreshed DOM and applies CSS styles which takes a while. It has a negative effect on my script: when these operations are not complete before I measure the width — my script gets a wrong value. If I perform the measure in a second — everything is ok.
The thing I'm looking for is a way to detect the moment when the <ul>
is fully drawn, styles applied and the width has stabilizes. Or at least a way to detect every dimensions changes. Of course I can use setTimeout(..., 100)
but it's ugly and I guess — not a solution at all.
If there's a way to detect width stabilization — I would do the measuring right after it to get the correct values.
HTML code generated by the DOM
<div>
<ul>
<li><a href="...">1</a></li>
<li><a href="...">2</a></li>
....
</ul>
</div>
P.S. Why I need this. My paginator's left-floating <li>
items tend to move to the next line when the <ul>
tries to become wider than the page itself. Even though most of <li>
s are invisible because of parent <div>
's width restriction:
div { width: 500px; overflow: hidden; }
div ul { width: 100%; white-space: nowrap; }
div ul li { display: block; float: left; }
they still go down unless I specify the actual summed width of the <ul>
with the script.
我发现,当我将 CSS 嵌入到文档中时,一切都很好。这证明问题是尽管我使用
$(document).ready()
进行初始化,但我的 CSS 文件尚未加载。当依赖外部资源并愿意正确测量宽度时,应该使用
$(window).load()
。I've discovered that when I embed CSS into the document — everything's fine. This proves that the problem was my CSS files have not been loaded despite I used
$(document).ready()
for initializing.One should use
$(window).load()
when relying on external resources and willing to measure widths correctly.