document.ready vs document.onLoad [英] document.ready vs document.onLoad

查看:78
本文介绍了document.ready vs document.onLoad的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am wondering which one is the right one to run the js code which calculates the height of vertical menu depending on the window height and sets it on time, not late, not early.

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

I am using document.ready but it is not really helping me with the issue, it is not setting sometimes, I have to reload the page, then it is working, but not on the first load.

如何解决这个问题?

这是我的代码:

$(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已加载 - 但不是像图像那样。如果图像会影响高度和宽度,并且图片标签没有设置宽度和高度,那么就不能选择就绪 - 否则可能就是。

When you run code when the document is ready, it means the DOM is loaded - but not things like images. If images will affect the height and width and the image tag has no width and height set, ready isn't the choice for you - otherwise it probably is.

onload

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

This includes images - so everything will be loaded. This means it fires a bit later.

两者

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 ;

这篇关于document.ready vs document.onLoad的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆