jQuery bind/unbind 'scroll' event on $(win

2019-01-17 14:11发布

I have this function:

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

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.

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.

6条回答
Ridiculous、
2楼-- · 2019-01-17 14:29
$(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.

Update

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).

查看更多
别忘想泡老子
3楼-- · 2019-01-17 14:30

You need to:

unbind('scroll')

At the moment you are not specifying the event to unbind.

查看更多
家丑人穷心不美
4楼-- · 2019-01-17 14:32

try this:

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

it works in my project

查看更多
做自己的国王
5楼-- · 2019-01-17 14:36

Note that the answers that suggest using unbind() are now out of date as that method has been deprecated and will be removed in future versions of jQuery.

As of jQuery 3.0, .unbind() has been deprecated. It was superseded by the .off() method since jQuery 1.7, so its use was already discouraged.

Instead, you should now use off():

$(window).off('scroll');
查看更多
\"骚年 ilove
6楼-- · 2019-01-17 14:41

Try this instead

$.unbind('scroll');

http://api.jquery.com/unbind/

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2019-01-17 14:49

Very old question, but in case someone else stumbles across it, I would recommend trying:

$j("html, body").stop(true, true).animate({
        scrollTop: $j('#main').offset().top 
}, 300);
查看更多
登录 后发表回答