我想知道哪一个是正确的运行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';
});
});
发布于 2012-11-17 00:52:37
ready
当您在文档准备就绪时运行代码时,这意味着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 ;
https://stackoverflow.com/questions/13420811
复制相似问题