JavaScript:检查& lt; div& gt;的宽度放置物体之前 [英] JavaScript: Check width of a <div> object before placing it
问题描述
考虑:
$("#PlotPlace").append('<div style="position:absolute;left:200px;top:40px;font-size:smaller">Hello world!</div>');
仅当结果文本的宽度小于60px时才需要执行该行.在放置物体之前如何检查宽度?
I need to execute that line only if the width of the resultant text would be less than 60px. How can I check the width before placing the object?
推荐答案
不幸的是,一旦将div渲染到DOM中,div就会只有一个宽度值.
Unfortunately, the div will only have a width value once it is rendered into the DOM.
我会将内容附加到文档的不显眼区域,甚至放置在绝对位置,以免发生流中断,并确保将其设置为"visibility:hidden".这样,它将被插入到DOM中并进行渲染,但对于查看者是不可见的.
I would append that content to an inconspicuous area of the document, perhaps even absolutely positioned so that no flow disruption occurs, and make sure that it is set to "visibility:hidden". That way it will be inserted into the DOM and be rendered, but be invisible to the viewer.
然后可以检查其宽度,然后将其移动到适当的位置并将其设置为"visibility:visible".否则,您可以将其从文档中删除.
You can then check the width on it, and move it into position and set it to "visibility:visible" at that point. Otherwise, you can remove it from the document.
这篇关于JavaScript:检查& lt; div& gt;的宽度放置物体之前的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!