所以我目前使用的是:
$(window).resize(function(){resizedw();});
但是在调整大小过程中,这个函数会被调用很多次。是否有可能在事件结束时捕获事件?
所以我目前使用的是:
$(window).resize(function(){resizedw();});
但是在调整大小过程中,这个函数会被调用很多次。是否有可能在事件结束时捕获事件?
当前回答
这是我用来延迟重复操作的,它可以在你的代码中的多个地方调用:
function debounce(func, wait, immediate) {
var timeout;
return function() {
var context = this, args = arguments;
var later = function() {
timeout = null;
if (!immediate) func.apply(context, args);
};
var callNow = immediate && !timeout;
clearTimeout(timeout);
timeout = setTimeout(later, wait);
if (callNow) func.apply(context, args);
};
};
用法:
$(window).resize(function () {
debounce(function() {
//...
}, 500);
});
其他回答
我自己写了一个小包装函数…
onResize = function(fn) {
if(!fn || typeof fn != 'function')
return 0;
var args = Array.prototype.slice.call(arguments, 1);
onResize.fnArr = onResize.fnArr || [];
onResize.fnArr.push([fn, args]);
onResize.loop = function() {
$.each(onResize.fnArr, function(index, fnWithArgs) {
fnWithArgs[0].apply(undefined, fnWithArgs[1]);
});
};
$(window).on('resize', function(e) {
window.clearTimeout(onResize.timeout);
onResize.timeout = window.setTimeout("onResize.loop();", 300);
});
};
用法如下:
var testFn = function(arg1, arg2) {
console.log('[testFn] arg1: '+arg1);
console.log('[testFn] arg2: '+arg2);
};
// document ready
$(function() {
onResize(testFn, 'argument1', 'argument2');
});
有一个优雅的解决方案使用下划线。js所以,如果你在你的项目中使用它,你可以做以下-
$( window ).resize( _.debounce( resizedw, 500 ) );
这应该足够了:)但是,如果你有兴趣阅读更多,你可以查看我的博客文章- http://rifatnabi.com/post/detect-end-of-jquery-resize-event-using-underscore-debounce(deadlink)
就窗口管理器而言,每个调整大小事件都是它自己的消息,具有不同的开始和结束,因此从技术上讲,每次调整窗口大小时,它都是结束。
话虽如此,也许你想推迟你的延续?举个例子。
var t = -1;
function doResize()
{
document.write('resize');
}
$(document).ready(function(){
$(window).resize(function(){
clearTimeout(t);
t = setTimeout(doResize, 1000);
});
});
下面是一个非常简单的脚本,可以在窗口对象上触发'resizestart'和'resizeend'事件。
没有必要在日期和时间上浪费时间。
变量d表示在触发调整大小结束事件之前,调整大小事件之间的毫秒数,您可以使用它来更改结束事件的灵敏度。
要收听这些事件,你所需要做的就是:
resizestart: $(窗口)。on(' Resize Start ', function(event){console.log('Resize Start!');});
resizeend: 美元(窗口)。on('resizeend', function(event){console.log(' resizeend !');});
(function ($) {
var d = 250, t = null, e = null, h, r = false;
h = function () {
r = false;
$(window).trigger('resizeend', e);
};
$(window).on('resize', function (event) {
e = event || e;
clearTimeout(t);
if (!r) {
$(window).trigger('resizestart', e);
r = true;
}
t = setTimeout(h, d);
});
}(jQuery));
我很幸运地推荐了以下网站:http://forum.jquery.com/topic/the-resizeend-event
下面是代码,这样你就不必去挖掘他的帖子的链接和源代码:
var rtime;
var timeout = false;
var delta = 200;
$(window).resize(function() {
rtime = new Date();
if (timeout === false) {
timeout = true;
setTimeout(resizeend, delta);
}
});
function resizeend() {
if (new Date() - rtime < delta) {
setTimeout(resizeend, delta);
} else {
timeout = false;
alert('Done resizing');
}
}
谢谢森那美。Vidas for code!