jQuery在$(window)上绑定/取消绑定'scroll'事件 [英] jQuery bind/unbind 'scroll' event on $(window)

查看:246
本文介绍了jQuery在$(window)上绑定/取消绑定'scroll'事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我具有此功能:

function block_scroll(key){
    if (key) {
        $(window).bind("scroll", function(){
            $('html, body').animate({scrollTop:0}, 'fast');
        });
    } else {
        $(window).unbind();
    }
}

第一部分可以正常工作,但是当我稍后调用block_scroll(false)时,它仍然处于阻塞状态. ?

The first part works as it should, but when I later call block_scroll(false) - it's still blocking. Wat do?

重新编辑 所以按照建议我尝试了...

RE-EDIT So as suggested I tried...

$(window).unbind("scroll");

...有些困惑.最初它没有用-然后就起作用了.

...with some confusion. At first it didn't work - then it worked.

现在我认为它失败了,因为我正在滚动调用block_scroll(false)的那一刻.我已经对此进行了几次测试.是的,如果我在脚本运行时不执行任何操作,并且调用了block_scroll(false)-它确实起作用.但是,如果我在滚动时没有滚动它,就不会如此.

Now I think it failed because I was scrolling the moment block_scroll(false) was called. I've tested this several times now. And yes, if I do nothing while the script runs and block_scroll(false) is called - it does work. But it doesn't if I'm scrolling when it's called.

推荐答案

$(window).unbind('scroll');

即使文档表示,如果不带任何参数调用,它将删除所有事件处理程序,但这是值得尝试显式解除绑定.

Even though the documentation says it will remove all event handlers if called with no arguments, it is worth giving a try explicitly unbinding it.

如果您使用单引号,它会起作用吗?听起来不对-就我所知,JavaScript将单引号和双引号视为相同(不同于其他一些语言,如PHP和C).

It worked if you used single quotes? That doesn't sound right - as far as I know, JavaScript treats single and double quotes the same (unlike some other languages like PHP and C).

这篇关于jQuery在$(window)上绑定/取消绑定'scroll'事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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