jQuery $(window).resize() not working when decreas

2019-04-10 18:40发布

问题:

I have a div with an id "main", I want to set its height using jQuery and making so that on window.resize its height is modified using a function but for some reason it works well only when increasing window's height, when decreasing it it doesn't work.

This is the JS:

function setMainH() {
    var docH = $(document).height();
    $("#main").height(docH - 40);
}

$(function() {
    setMainH();
});

$(window).resize(function() {
    setMainH();
});

EDIT: the problem appears either increasing or decreasing

EDIT 2: the resize() event seem to be called correctly, I've tried with

console.log("resizing");

on resizing and it logs correctly so the problem isn't that.

回答1:

$(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.



回答2:

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/