如何解决如何一致地获取$document.ready中包含图像的DIV的高度仅在Webkit中存在问题
我有这个片段来演示问题:<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或诺基亚N800上基于旧Webkit版本构建的Tear)上,该数字为0。
如果细分的内容不是图像,或者该图像是主细分的直接子级(即没有细分),则不会出现问题。即使页面和图像都来自文件URL也确实会发生(即不依赖于网络延迟)。
我可以做一个简单的更改,以在页面加载时正确获取该高度值,但保持DIV结构不变?
解决方法
用
$(window).load()
代替$(document).ready()
。
$(window).load(function() {
var hyt = $(\'#opts\').height();
var div_for_later = $(\'#opts\').detach();
$(\'#hytmsg\').text(\'\'+hyt);
$(\'body\').append(div_for_later);
});
因为$(document).ready()
仅检查是否已创建所有DOM元素,而$(window).load()
实际上在加载所有页面内容(包括图像)时触发。
, http://api.jquery.com/ready/
Ready特别会在加载图像之前触发,因此在您的脚本运行时不会加载它们。
您可以使用$(window).load(function () {
代替ready。
, 通过style属性或CSS将height值添加到img标签。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。