简体   繁体   English

为什么document.ready不能一直工作?

[英]why document.ready not always work?

I have this very simple function to resize a div according to an element on the page. 我有这个非常简单的功能,可以根据页面上的元素调整div的大小。
Because of the static navigation bar on top of the page, I need to control the empty space underneath it, for the first div with content to appear on the right place (below the navigation bar), specially because when the screen is smaller, the navigation bar gets larger (height is bigger). 由于页面顶部的静态导航栏,我需要控制其下方的空白区域,以便将第一个div内容显示在正确的位置(导航栏下方),特别是因为当屏幕较小时,导航栏变大(高度变大)。
My question is: why does it not always work? 我的问题是:为什么它并不总是有效? It works fine most of the times, but sometimes I need to refresh the page for it to work. 在大多数情况下,它都能正常工作,但有时我需要刷新页面才能使其正常工作。
Here is the dummy HTML: 这是虚拟HTML:

<div id="menu-fixed-top"></div>
<div id="empty-space"></div>
<div id="content"></div>

where the #empty-space is the div I want to control the height. #empty-space是我要控制高度的div。
I used the document.ready and the window.resize to control it. 我使用document.readywindow.resize来控制它。 The JQuery function is: JQuery函数是:

$(document).ready(function() {
  var height = $("#menu-fixed-top").innerHeight();
  $("#empty-space").height( height );
    $(window).resize(function() {
      $("#empty-space").height( height );
   });
});

Is there any way to get it working 100% of the time? 有什么方法可以使其100%地正常工作吗? Or the only way is to be sure is to use media queries? 还是唯一可以确定的是使用媒体查询?
Thanks 谢谢

document.ready will trigger when the whole DOM has loaded and is ready for javascript to execute. 当整个DOM已加载并准备好执行JavaScript时,document.ready将触发。 This is to avoid any problems with javascript being ready to go but the whole DOM hasn't finished loading. 这是为了避免JavaScript准备就绪但整个DOM尚未完成加载时出现任何问题。

http://learn.jquery.com/using-jquery-core/document-ready/ http://learn.jquery.com/using-jquery-core/document-ready/

I would first check to see that the DOM has finished loading without document.ready being triggered before drawing the conclusion that jquery isn't kicking it off. 我首先要检查一下DOM是否已完成加载而没有document.ready被触发,然后得出jquery尚未启动的结论。

You may also want to look at window.load if you're wanting to calculate heights and such as the DOM != the fully rendered page 如果您想计算高度,例如DOM!=完全渲染的页面,则可能还需要查看window.load。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM