我使用.resize()
函数来检测窗口大小调整事件,但它同时检测高度和宽度的变化。
有没有办法只检测宽度变化的,而不检测高度变化的?
发布于 2012-05-25 16:06:17
var width = $(window).width();
$(window).on('resize', function() {
if ($(this).width() !== width) {
width = $(this).width();
console.log(width);
}
});
发布于 2016-02-05 22:53:49
尽管已经有几个有效解决方案的答案,但这类任务对性能至关重要(当用户调整窗口大小时,窗口大小调整事件会触发多次),因此我强烈建议您关注性能。请看下面优化后的代码:
/* 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;
}
});
此外,您可能会对检查Debounce / Throttle模式感兴趣-在这样的情况下,它们会极大地提高性能。
发布于 2015-12-14 22:04:06
你也可以使用这个小的jQuery插件:https://github.com/adjohnson916/jquery-resize-dimension
使您自己的代码更具可读性:
ResizeDimension.bind('width');
$(window).on('resize-width', function () {
console.log('resize-width event');
});
或者只是:
$(window).resizeDimension('width', function () {
console.log('resize-width event');
});
https://stackoverflow.com/questions/10750603
复制相似问题