在jquery中多次触发window.resize [英] window.resize in jquery firing multiple times
问题描述
我在HTML文件中有以下javascript / jquery代码:
I have the following javascript/jquery code in an HTML file:
<html>
<head>
<script src="http://code.jquery.com/jquery-1.6.2.min.js"
type="text/javascript"></script>
<script language="javascript">
$(window).resize(function(){alert('hi');});</script>
</head>
<body>
resize me
</body>
</html>
它看起来相对简单,但是当我调整浏览器窗口大小时,我会得到两个连续的警报窗口在Chrome和IE9上我看似崩溃FF5。
It appears relatively straight forward, however when I re size the browser window, I get two successive alert windows on Chrome and IE9 and I seemingly crash FF5.
我缺少什么?每个维度(x / y)是一个火吗?
What am I missing? Is it one fire per dimension (x/y)?
推荐答案
你知道了,有些浏览器会在调整大小时启动并再次启动,而其他浏览器会像FF一样连续启动。解决方法是使用 setTimeout
来避免一直触发。可以在此处找到一个示例。以下是来自相同参考的代码:
You got it, some browsers fire on resize start and again on end while others like FF fire continuously. Solution is to use setTimeout
to avoid firing all the time. An example can be found here. Here is the code from the same reference:
(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');
// usage:
$(window).smartresize(function(){
// code that takes it easy...
});
这篇关于在jquery中多次触发window.resize的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!