Detect a window width change but not a height change

后端 未结 5 1857
傲寒
傲寒 2020-12-24 01:35

I\'m using the .resize() function to detect window re-size events, but this detects both height and width changes.

Is there any way to detect ju

5条回答
  •  生来不讨喜
    2020-12-24 01:59

    you can detect both events and just execute code when it's a width change:

    var lastWidth = $(window).width();
    
    $(window).resize(function(){
       if($(window).width()!=lastWidth){
          //execute code here.
          lastWidth = $(window).width();
       }
    })        
    

    And you might want to check event debouncing.

    Debouncing enforces that a function not be called again until a certain amount of time has passed without it being called. As in "execute this function only if 100 milliseconds have passed without it being called.


    Read more:


    • https://css-tricks.com/the-difference-between-throttling-and-debouncing/
    • https://davidwalsh.name/javascript-debounce-function

提交回复
热议问题