追加后的DIV宽度立即计算错误吗? [英] DIV width immediately after append is calculating wrong?

查看:79
本文介绍了追加后的DIV宽度立即计算错误吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我正在处理的脚本中,我将用于反馈形式的标记附加到主体,然后使用jQuery将该元素(DIV)居中显示在屏幕上.在下面的代码示例中,form_code保存了我的表单标记.为#feedback_form定义的CSS样式明确定义了宽度.但是,在追加之后立即调用的width()的计算计算错误,返回的尺寸几乎等于页面的整个宽度.

In the script I'm working on, I'm appending markup for a feedback form to the body and then centering that element (a DIV) on screen with jQuery. In the code sample below, form_code holds my form markup. The defined CSS styles for #feedback_form explicitly define a width. However, the calculation for width() called immediately after appending is calculating wrong, returning a dimension almost equal to the entire width of the page.

如果我用控制台警告宽度,即使几秒钟后,它也可以正确计算.从来没有遇到过这个问题,有人可以对此有所了解吗?

If I alert the width with console, even seconds later, it calculates correctly. Never run into this before, can somebody shed some light on this?

jQuery('body').append(form_code);
alert(jQuery("#feedback_form").css("width"));

推荐答案

您的Javascript代码正在与呈现HTML的线程不同的线程中运行.如果您在添加新代码后立即查询宽度,则呈现线程将没有时间重新布局页面,因此您可以得到旧的或可能是中间的宽度.

Your Javascript code is running in a different thread to the one that renders the HTML. If you query the width immediately after adding new code the render thread won't have had time to relayout the page so you get the old, or possibily an intermediate, width.

我不确定新浏览器是否会出现这种情况,但是肯定旧的浏览器会协同工作,因此在您明确暂停以允许更新之前,页面不会更新.

I'm not sure if this is the case with newer browsers but certainly old ones were co-operatively multitasking so the page wouldn't update until you explicitly paused to allow it to update.

如果使用以下代码,您会发现它起作用,因为零秒暂停实际上允许浏览器处理rerender事件.

If you use the following code you'll find it works because the zero second pause actually allows the browser to process the rerender event.

function show_width() {
    alert(jQuery("#feedback_form").css("width"));
}
setTimeout(show_width, 0);

这篇关于追加后的DIV宽度立即计算错误吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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