javascript jQuery - 如何知道窗口是否在调整宽度/高度或两者?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12661111/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 16:48:22  来源:igfitidea点击:

jQuery - How to know if window is resizing in width/height or both?

javascriptjqueryresizewindow

提问by user1257255

I have a little problem with window resizing using jQuery's function .resize(). I would like to know which dimension is getting bigger/smaller - width or height. I need this because if I just put two conditions - if width is for 50px bigger than div and if height is for 50px bigger than div,

我在使用 jQuery 的函数.resize()调整窗口大小时遇到​​了一些问题。我想知道哪个尺寸变大/变小 - 宽度或高度。我需要这个,因为如果我只提出两个条件 - 如果宽度比 div 大 50px,如果高度比 div 大 50px,

// (pseudocode)
if width = div.width + 50px
   width = something
if height = div.height + 50px
   height = something

then is working on just one condition and I can resize only width or height.

然后只处理一种情况,我只能调整宽度或高度。

How could I know which dimension is changing in size or if both are?

我怎么知道哪个维度的大小在变化,或者两者都在变化?

回答by Anoop

By saving last window size values in variables.

通过在变量中保存最后一个窗口大小值。

var h = $(window).height(), w = $(window).width();
$(window).resize(function(){

    var nh = $(window).height(), nw = $(window).width();
     // compare the corresponding variables.
    h = nh; w = nw; // update h and w;
});

回答by techfoobar

Save the previous size and compare with it, everytime the size changes.

保存之前的尺寸并与它进行比较,每次尺寸发生变化时。

For ex:

例如:

var prevW = -1, prevH = -1;

$(document).ready(function() {

    // ... other stuff you might have inside .ready()

    prevW = $(window).width();
    prevH = $(window).height();
});

$(window).resize(function() {
    var widthChanged = false, heightChanged = false;
    if($(window).width() != prevW) {
        widthChanged  = true;
    }
    if($(window).height() != prevH) {
        heightChanged = true;
    }

    // your stuff

    prevW = $(window).width();
    prevH = $(window).height();

});

Demo:http://jsfiddle.net/44aNW/

演示:http : //jsfiddle.net/44aNW/