How to get height of image-containing DIV in $(document).ready() consistently (problem in Webkit only)
I have this fragment that demonstrates the problem:
<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>
Load it in Opera or Gecko and the number in list item 3 is something sensible like 53. Load it in a Webkit browser (Chrome 12 on my Windows machine, or Tear, built on an old Webkit version, on my Nokia N800), and the number is 0.
Problem doesn't oc开发者_如何学Gocur if the content of the subdiv is not an image, or if the image is a direct child of the main div (i.e. no subdiv). It does occur even if the page and image are both from file: URLs (i.e., not dependent on network lag).
What's a simple change I can make to get that height value correctly on page load, but keep the DIV structured as is?
$(window).load()
instead of $(document).ready()
.
$(window).load(function() {
var hyt = $('#opts').height();
var div_for_later = $('#opts').detach();
$('#hytmsg').text(''+hyt);
$('body').append(div_for_later);
});
Because $(document).ready()
only checks for all DOM elements to have been created, while $(window).load()
actually trigger when all page content has been loaded, including images.
http://api.jquery.com/ready/
Ready specifically fires prior to images being loaded, therefore they are not loaded when your script runs.
You can use $(window).load(function () {
instead of ready.
Add a height value to the img tag via either the style attribute, or CSS.
精彩评论