Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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 occur 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?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
872 views
Welcome To Ask or Share your Answers For Others

1 Answer

$(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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...