【发布时间】:2012-04-15 14:08:23
【问题描述】:
我有一个演示问题的片段:
<html>
<head>
<title>height query demo</title>
<script type="text/javascript" src="http://code.jquery.com/jquery-1.6.1.min.js"></script>
</head>
<body>
<div id="opts" style="font-size:24px; text-align: center; margin: 10px auto;">
<div>
<img src="http://static.jquery.com/files/rocker/images/logo_jquery_215x53.gif"
alt="jquerylogo"/>
</div>
</div>
<h1>Demo of querying height</h1>
<p>The source code of this document has a DIV prior to the H1. The DIV contains a
subdiv which in turn contains an image.<br />
Using jQuery's <tt>$(document).ready</tt>, the following processing takes place:</p>
<ol><li>DIV queried for its height</li>
<li>DIV detached from the document</li>
<li>height value written out here:
<span style="font-size: larger; color: magenta;" id="hytmsg"/></li>
<li>DIV attached at end of document</li></ol>
<script type="text/javascript">
$(document).ready(function() {
var hyt = $('#opts').height();
var div_for_later = $('#opts').detach();
$('#hytmsg').text(''+hyt);
$('body').append(div_for_later);
});
</script>
</body>
<html>
在 Opera 或 Gecko 中加载它,列表项 3 中的数字是合理的,例如 53。 将其加载到 Webkit 浏览器(我的 Windows 机器上的 Chrome 12 或 Tear,在我的诺基亚 N800 上基于旧的 Webkit 版本构建),数字为 0。
如果 subdiv 的内容不是图像,或者图像是主 div 的直接子级(即没有 subdiv),则不会出现问题。即使页面和图像都来自文件:URL(即不依赖于网络延迟),它也会发生。
为了在页面加载时正确获取高度值,但保持 DIV 结构不变,我可以做哪些简单的更改?
【问题讨论】:
-
请注意,您的 Javascript 不需要放在页面底部,它可以放在 HEAD 标记之后(不知道是否存在性能差异,但由于 Webkit 在页面加载时编译 javascript ,可能会影响性能)
-
我不久前读到过,特别是对于文档就绪样式脚本,将它们放在最后被认为是更好的做法。我的实时页面中的大多数脚本标签都在 HEAD 中;我在 BODY 端只有一个小的,它调用各种初始化函数。
-
总是把你的JS放在页面底部,这样页面加载速度会更快。除非您现在必须执行脚本,否则大多数时候您将使用 $(document).ready 来等待 DOM 加载,这意味着您可以在所有 html 标记之后编写它们。