我有这个片段来演示这个问题:
<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.
如果细分的内容不是图像,或者图像是主div的直接子节点(即没有细分),则不会出现问题.即使页面和图像都来自文件:URL(即,不依赖于网络延迟),它确实会发生.
我可以在页面加载时正确地获得高度值的简单更改,但保持DIV结构不变?