Javascript document.ready与document.onLoad

Javascript document.ready与document.onLoad,javascript,jquery,onload,document-ready,Javascript,Jquery,Onload,Document Ready,我想知道哪个是运行js代码的正确方法,js代码根据窗口高度计算垂直菜单的高度,并将其设置为准时、不晚、不早 我正在使用document.ready,但它并没有真正帮助我解决这个问题,有时它没有设置,我必须重新加载页面,然后它才能工作,但不是在第一次加载时 如何解决这个问题 这是我的密码: $(document).ready(function(){ var winh = document.body.clientHeight; var footer = document.getE

我想知道哪个是运行js代码的正确方法,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';
     });
});
准备就绪

当您在文档准备就绪时运行代码时,这意味着加载了DOM,但不是像图像这样的东西。如果图像会影响高度和宽度,并且图像标记没有设置宽度和高度,则ready不是您的选择,否则可能是

onload

这包括图像-因此所有内容都将被加载。这意味着它会晚一点发射

两者都有

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 ;

在加载页面之前是否调整大小?在设置就绪之前可以调用Your window.resize。@AJak ready和resize做同样的事情,@AJak虽然示例中的制表符是错误的,但是resize事件被添加到
ready
函数中,因此它不能在前面的代码之前触发。另请参见:很好,这应该是答案,让我先试试:我把所有这些代码放在头上的一个标签里,可以吗?但是,它似乎不适用于具有图像的页面。任何原因
$(窗口)。resize(calculateSize)
位于
文档中。准备好了吗?为什么不简单:
$(document).ready(calculateSize)$(窗口)。在('resize load',calculateSize)
?@JosephSilber问得好。取决于是否要在DOM准备就绪之前侦听调整大小。这可能是一个边缘案件。