调整窗口大小后触发一个函数 [英] fire a function after window resize

查看:245
本文介绍了调整窗口大小后触发一个函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 $(window).resize()上做了几个函数。其中一个函数,是一个有很多div的复杂动画。

  $ window.resize(function(){
//一些函数
doAnim();
}

问题在于, resize()函数触发了很多。是否可以在 resize()已完成,它没有发射过百次?



干杯

解决方案
  var idt; 
$(window).resize (function(){
if(idt)clearTimeout(idt);
idt = setTimeout(doAnim,500);
}

您也可以使用闭包来避免污染全局范围然而,这里的要点是,每当用户调整窗口大小时,它都会设置一个超时时间并清除前一个:仅当用户离开窗口而不调整其大小半秒时,才会执行 doAnim 函数。当然你可以设置自己的延迟。


I'm doing a few functions on $(window).resize(). One of the functions inside it, is a complex animation with lots of divs.

$window.resize(function() {
    // some functions
    doAnim();
}

the problem here is, that the resize() function triggers a lot. Is it possible to fire one function after the resize() is finished, that it doesnt fire a hundred times?

Cheers

解决方案

So, I believe this is a similar scenario when a user "type" something: you can't know when the user finished to compose a sentence, the same here, you don't know when the user has finished to resize; so what you can do is have an acceptable interval:

var idt;
$(window).resize(function() {
    if (idt) clearTimeout(idt);
    idt = setTimeout(doAnim, 500);
}

You can also use a closure to avoid to pollute the global scope with idt variable.

However the main point here is that every time the user resize the window, it set a timeout and clear the previous one: the doAnim function will be executed only if the user leave the window without resizing it for half second. Of course you can set your own delay.

这篇关于调整窗口大小后触发一个函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆