jQuery 绑定/取消绑定“滚动” $(window) 上的事件
我有这个功能:
function block_scroll(key){
if (key) {
$(window).bind("scroll", function(){
$('html, body').animate({scrollTop:0}, 'fast');
});
} else {
$(window).unbind();
}
}
第一部分按其应有的方式工作,但是当我稍后调用 block_scroll(false) 时 - 它仍然处于阻塞状态。做什么?
重新编辑 因此,按照建议,我尝试了......
$(window).unbind("scroll");
但有些困惑。起初它不起作用 - 然后它起作用了。
现在我认为它失败了,因为我在调用 block_scroll(false) 时正在滚动。我现在已经测试过好几次了。是的,如果我在脚本运行时什么都不做并且调用 block_scroll(false) - 它确实有效。但如果我在调用它时滚动,则不会。
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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
尽管文档说如果不带参数调用它将删除所有事件处理程序,但值得给出一个尝试显式解除绑定。
更新
如果您使用单引号,它会起作用吗?这听起来不对——据我所知,JavaScript 将单引号和双引号视为相同(与 PHP 和 C 等其他语言不同)。
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).
请注意,建议使用
unbind()
的答案现已过时,因为 该方法已已弃用并将在 jQuery 的未来版本中删除。相反,您现在应该使用
off()
: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.Instead, you should now use
off()
:试试这个
http://api.jquery.com/unbind/
Try this instead
http://api.jquery.com/unbind/
试试这个:
它适用于我的项目
try this:
it works in my project
您需要:
目前您没有指定要解除绑定的事件。
You need to:
At the moment you are not specifying the event to unbind.
非常老的问题,但如果其他人偶然发现它,我建议尝试:
Very old question, but in case someone else stumbles across it, I would recommend trying: