【问题标题】:How to get height of image-containing DIV in $(document).ready() consistently (problem in Webkit only)如何始终如一地获取 $(document).ready() 中包含图像的 DIV 的高度(仅在 Webkit 中存在问题)
【发布时间】:2012-04-15 14:08:23
【问题描述】:

我有一个演示问题的片段:

<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 或 Tear,在我的诺基亚 N800 上基于旧的 Webkit 版本构建),数字为 0。

如果 subdiv 的内容不是图像,或者图像是主 div 的直接子级(即没有 subdiv),则不会出现问题。即使页面和图像都来自文件:URL(即不依赖于网络延迟),它也会发生。

为了在页面加载时正确获取高度值,但保持 DIV 结构不变,我可以做哪些简单的更改?

【问题讨论】:

  • 请注意,您的 Javascript 不需要放在页面底部,它可以放在 HEAD 标记之后(不知道是否存在性能差异,但由于 Webkit 在页面加载时编译 javascript ,可能会影响性能)
  • 我不久前读到过,特别是对于文档就绪样式脚本,将它们放在最后被认为是更好的做法。我的实时页面中的大多数脚本标签在 HEAD 中;我在 BODY 端只有一个小的,它调用各种初始化函数。
  • 总是把你的JS放在页面底部,这样页面加载速度会更快。除非您现在必须执行脚本,否则大多数时候您将使用 $(document).ready 来等待 DOM 加载,这意味着您可以在所有 html 标记之后编写它们。

标签: jquery webkit


【解决方案1】:

$(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() 实际上会在所有页面内容(包括图像)已加载时触发。

【讨论】:

  • 谢谢,太棒了
【解决方案2】:

http://api.jquery.com/ready/

Ready 在加载图像之前专门触发,因此在您的脚本运行时不会加载它们。

您可以使用 $(window).load(function () { 代替 ready。

【讨论】:

    【解决方案3】:

    通过样式属性或 CSS 向 img 标签添加高度值。

    【讨论】:

    • 这也可以,但是如果我更改图像会产生一个小的维护问题,我也需要更改源。
    猜你喜欢
    • 2020-04-25
    • 2013-03-11
    • 1970-01-01
    • 2013-07-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多