窗口调整大小事件在jQuery中触发两次

窗口调整大小事件在jQuery中触发两次

本文介绍了窗口调整大小事件在jQuery中触发两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我运行了以下代码

$(document).ready(function() {

    var ivar = 0;

    $(window).resize(function() {
        console.log('$(window).height() ' + $(window).height() + ' - ' + ++ivar);
    });
});​

每当我调整大小时,我都会发现事件触发了两次,即计数器"ivar"增加了两次.

whenever i resize i found the event was firing twice i.e. the counter 'ivar' is incremented twice.

任何人都可以告诉我在调整大小事件中发生了什么,这会使计数器两次被放大

Can any one advise me whats happening in the resize event that makes the counter to get incremeted twice

* * 1.我通过双击窗口栏来调整窗口大小.

** 1. I'm resizing the window by double-clicking on the window bar.

谢谢

推荐答案

这是众所周知的问题.在某些浏览器中,调整大小被两次调用.我们可以创建计时器,以便仅在用户停止调整窗口大小时才调用我们的函数.这是您的操作方法:

That's the very well known problem. In some browsers resize is called twice. We can create timer so it will call our function only when the user stops resizing the window.Here's how you can do it:

var globalTimer = null;

$(window).resize(function() {
    clearTimeout(globalTimer);
    globalTimer = setTimeout(doneResize, 500);
});

function doneResize(){
  console.log('$(window).height() ' + $(window).height() + ' - ' + ++ivar);
}​

这篇关于窗口调整大小事件在jQuery中触发两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-04 21:30