【问题标题】:document.ready vs document.onLoaddocument.ready 与 document.onLoad
【发布时间】:2012-11-16 16:43:48
【问题描述】:

我想知道哪一个是正确的运行 js 代码,它根据窗口高度计算垂直菜单的高度并按时设置,不迟到,不早。

我正在使用document.ready,但它并没有真正帮助我解决这个问题,有时它没有设置,我必须重新加载页面,然后它才能工作,但不是在第一次加载时。

如何解决这个问题?

这是我的代码:

$(document).ready(function(){
     var winh = document.body.clientHeight;
     var footer = document.getElementById('footer').offsetHeight;
     document.getElementById('sidebar').style.height = winh - 5/2*footer + 'px';
     document.getElementById('sidebar').style.marginBottom = footer + 'px';

     $(window).resize(function(){
         var winh = document.body.clientHeight;
         var footer = document.getElementById('footer').offsetHeight;
         document.getElementById('sidebar').style.height = winh - 5/2*footer + 'px';
         document.getElementById('sidebar').style.marginBottom = footer + 'px';
     });
});

【问题讨论】:

  • 您是否在页面加载之前调整大小?你的 window.resize 可以在 ready 设置之前被调用。
  • @AJak 准备和调整大小做同样的事情,
  • @AJak 虽然例子中的tabbing是错误的,但是在ready函数中添加了resize事件,所以不能在前面的代码之前触发。

标签: javascript jquery onload document-ready


【解决方案1】:

准备好了

当您在文档准备好时运行代码时,这意味着 DOM 已加载——但不是图像之类的东西。如果图像会影响高度和宽度,并且图像标签没有设置宽度和高度,那么 ready 不是您的选择 - 否则可能是。

加载

这包括图片 - 所以一切都会被加载。这意味着它会稍后触发。

两者

var calculateSize = function () {
     var winh = document.body.clientHeight;
     var footer = document.getElementById('footer').offsetHeight;
     document.getElementById('sidebar').style.height = winh - 5/2*footer + 'px';
     document.getElementById('sidebar').style.marginBottom = footer + 'px';
}

$(document).ready(function(){
    calculateSize();

     $(window).resize(calculateSize);
});

window.onload = calculateSize ;

【讨论】:

  • 很好,这应该是答案,让我先试试:D
  • 我把所有这些代码放在一个
  • 有什么理由 $(window).resize(calculateSize) 在 document.ready 里面?为什么不简单:$(document).ready(calculateSize); $(window).on('resize load', calculateSize)?
  • @JosephSilber 好问题。取决于您是否想在 DOM 准备好之前收听调整大小。这可能是一个边缘案例。
猜你喜欢
  • 2010-10-09
  • 2012-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-03-28
  • 2011-07-05
相关资源
最近更新 更多