jQuery - 检测窗口宽度变化但不检测高度变化

shr*_*ans 35 jquery resize responsive-design jquery-events

我正在使用该.resize()函数来检测窗口重新调整大小事件,但这会检测高度和宽度的变化.

有没有办法检测宽度变化而不是高度变化?

the*_*dox 74

var width = $(window).width();
$(window).on('resize', function() {
  if ($(this).width() != width) {
    width = $(this).width();
    console.log(width);
  }
});
Run Code Online (Sandbox Code Playgroud)


Tah*_*ksu 18

您可以检测这两个事件,只需在宽度更改时执行代码:

var lastWidth = $(window).width();

$(window).resize(function(){
   if($(window).width()!=lastWidth){
      //execute code here.
      lastWidth = $(window).width();
   }
})        
Run Code Online (Sandbox Code Playgroud)

你可能想检查事件去抖动.

Debouncing强制执行一个函数不会被调用,直到一定时间过去而没有被调用.正如在"执行此函数时,只有在没有被调用的情况下已经过了100毫秒.


阅读更多:



Ant*_*ton 5

尽管已经有几个工作解决方案的答案,但这种任务对性能至关重要(在用户调整窗口大小时多次触发窗口调整大小事件),因此我强烈建议您注意性能。请看下面的优化代码:

/* Do not waste time by creating jQuery object from window multiple times.
 * Do it just once and store it in a variable. */
var $window = $(window);
var lastWindowWidth = $window.width();

$window.resize(function () {
    /* Do not calculate the new window width twice.
     * Do it just once and store it in a variable. */
    var windowWidth = $window.width();

    /* Use !== operator instead of !=. */
    if (lastWindowWidth !== windowWidth) {
        // EXECUTE YOUR CODE HERE
        lastWindowWidth = windowWidth;
    }
});
Run Code Online (Sandbox Code Playgroud)

另外,您可能对检查去抖动/节流模式感兴趣- 在这种情况下,它们可以极大地提高性能。