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

前端 未结 2 930
Happy的楠姐
Happy的楠姐 2021-01-05 01:28

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 thi

2条回答
  •  滥情空心
    2021-01-05 01:52

    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/

提交回复
热议问题