Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
923 views
in Technique[技术] by (71.8m points)

jquery - 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 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

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

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...