当我尝试通过调用文本所在的文本来检查某些文本的宽度时.width()
,span
一开始我总是得到一个错误的值。那么为什么我.width()
再次打电话,我得到了正确的价值。
我正在添加文本,.append()
然后我想立即获得它的宽度。当我直接通过 Chrome 打开我的文件(不使用 Internet 访问 Dropbox.com)时,它在 99% 的时间内正确获取了宽度值。这可能是加载问题吗?
这是一个示例: https ://dl.dropboxusercontent.com/u/98788053/School/test.html
<script>
$(document).ready(function() {
$("body").append("<span id=\"element\">Text to measure</span>");
$("body").append("<div id=\"thewidth\"></div>");
$("body").append("<input type=\"button\" value=\"Try again\" onclick=\"getWidth();\">");
getWidth();
});
function getWidth()
{
$("#thewidth").html($("#element").width()+"px");
}
</script>