jQuery $(window).resize() not working when decreasing window's height

两盒软妹~` 提交于 2019-12-04 13:55:35
$(window).height();   // returns height of browser viewport
$(document).height(); // returns height of HTML document

So changing

var docH = $(document).height();

to

var docH = $(window).height();

will solve the problem.

I tested your code and it works fine in jsfiddle when running the JS without a wrapper in the body or head.

Demo of your code: http://jsfiddle.net/H5y5e/2/

You can however optimize your code a bit to clear-up the global space and cache the $(document) and $('#main') selectors so they doesn't have to be looked-up each resize event (which is a ton of events when the window resizes):

$(function() {
    var $document = $(document),
        $main     = $('#main');

    $(window).resize(function() {
        $main.height($document.height() - 40);
    }).trigger('resize');
});

Here is a demo: http://jsfiddle.net/H5y5e/1/

UPDATE

Also it seems like this can easily be done with just CSS (which is always good, takes care of the edge-case where someone has JS turned off):

#main {
    position : absolute;
    top      : 0;
    left     : 0;
    bottom   : 40px;
    width    : 100%;
}

Demo using just CSS: http://jsfiddle.net/H5y5e/3/

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!