我使用Paul爱尔兰Smartresize,但当我调整窗口大小时,resize()内的函数会多次触发,导致我的手风琴不能正常工作。有人知道为什么会发生这种情况吗?下面是正在运行的代码:http://jsfiddle.net/rebel2000/PnAH7/6/
$(document).ready( function(){
(function($,sr){
// debouncing function from John Hann
// http://unscriptable.com/index.php/2009/03/20/debouncing-javascript-methods/
var debounce = function (func, threshold, execAsap) {
var timeout;
return function debounced () {
var obj = this, args = arguments;
function delayed () {
if (!execAsap)
func.apply(obj, args);
timeout = null;
};
if (timeout)
clearTimeout(timeout);
else if (execAsap)
func.apply(obj, args);
timeout = setTimeout(delayed, threshold || 100);
};
}
// smartresize
jQuery.fn[sr] = function(fn){ return fn ? this.bind('resize', debounce(fn)) : this.trigger(sr); };
})(jQuery,'smartresize');
function anim3() {
$('#button').click(
function(){
if($(this).hasClass('active')){
$(this).animate({ "height": "30px"}, { queue:true, duration: 900 });
$(this).removeClass('active');
return false;
} else {
$(this).animate({ "height": "100px"}, { queue:true, duration: 900 });
$(this).addClass('active');
return false;
}
}
);
}
//anim3();
$(window).smartresize(function(){
anim3();
});
});发布于 2011-10-15 21:52:14
之所以会发生这种情况,是因为在调整大小时,re事件会多次触发。理论上(更多是为了说明目的),当JavaScript循环通过窗口大小的验证时,它会检测到它比以前更小/更大,并再次触发它。由于循环的速度非常快,所以在“单次”调整大小时,你会得到多个火。
你可以这样做:
var idCounter = 0;
$(window).smartresize(function(){
var myId=(++idCounter);
setTimeout(function(){
if(myId===idCounter){
anim3();
}
}, 500); // 500 milli the user most likely wont even notice it
}这应该安全地忽略多个火灾,并且只处理最后一个火灾。(除非你花了很多时间调整大小,否则你可以增加超时时间)
发布于 2011-10-16 06:08:29
下面是一段很棒的代码,它可以帮你处理这个问题:
http://benalman.com/projects/jquery-throttle-debounce-plugin/
另请参阅:
http://benalman.com/projects/jquery-dotimeout-plugin/
https://stackoverflow.com/questions/7778172
复制相似问题