调整大小之前之后 [英] Before after resize event

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

问题描述

我想在调整元素大小之前和之后做一些事情,我试图绑定resize事件,并且它起作用:

I would like to do something before and after resizing element, i have tried to bind resize event and it work:

$('#test_div').bind('resize', function(){
            // do something
});

我发现了一些问题,但是解决方法是timeout,我不想使用timeout.我只想立即处理:)

I have found some questions, but the solutions are timeout, i don't want to use timeout. I would just like to process immediately :)

另请参见:

感谢您的任何建议:)

推荐答案

没有大小调整结束事件可以听.知道用户何时完成调整大小的唯一方法是等待一段时间,直到不再有调整大小事件.这就是为什么该解决方案几乎总是涉及使用setTimeout()的原因,因为这是了解何时不再经过任何调整大小事件的最佳方式.

There is no such thing as a resize end event that you can listen to. The only way to know when the user is done resizing is to wait until some short amount of time passes with no more resize events coming. That's why the solution nearly always involves using a setTimeout() because that's the best way to know when some period of time has passed with no more resize events.

我以前的答案是侦听.scroll()事件,但它与.resize()完全相同:

This previous answer of mine listens for the .scroll() event, but it's the exact same concept as .resize(): More efficient way to handle $(window).scroll functions in jquery? and you could use the same concept for resize like this:

var resizeTimer;
$(window).resize(function () {
    if (resizeTimer) {
        clearTimeout(resizeTimer);   // clear any previous pending timer
    }
     // set new timer
    resizeTimer = setTimeout(function() {
        resizeTimer = null;
        // put your resize logic here and it will only be called when 
        // there's been a pause in resize events
    }, 500);  
}

您可以对计时器的500值进行试验,以了解您的喜欢程度.数字越小,它调用调整大小处理程序的速度就越快,但随后可能会被多次调用.数字越大,触发前的暂停时间就越长,但是在同一用户操作期间多次触发的可能性就较小.

You can experiment with the 500 value for the timer to see how you like it. The smaller the number, the more quickly it calls your resize handler, but then it may get called multiple times. The larger the number, the longer pause it has before firing, but it's less likely to fire multiple times during the same user action.

如果要在调整大小之前执行某些操作,则必须在收到的第一个调整大小事件上调用一个函数,然后在当前的调整大小操作期间不再调用该函数.

If you want to do something before a resize, then you will have to call a function on the first resize event that you get and then not call that function again during the current resize operation.

var resizeTimer;
$(window).resize(function () {
    if (resizeTimer) {
        clearTimeout(resizeTimer);   // clear any previous pending timer
    } else {
        // must be first resize event in a series
    }
     // set new timer
    resizeTimer = setTimeout(function() {
        resizeTimer = null;
        // put your resize logic here and it will only be called when 
        // there's been a pause in resize events
    }, 500);  
}

这篇关于调整大小之前之后的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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