jQuery 添加和删除 $(window).scroll(function()?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4306387/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 17:02:53  来源:igfitidea点击:

jQuery add and remove $(window).scroll(function()?

jquerywindowscrolltop

提问by Dee

How can I remove and then add the $(window).scroll? I need to store a variable and reuse it after some event.

如何删除然后添加$(window).scroll?我需要存储一个变量并在某个事件后重用它。

// here i store my var
$(window).scroll(function(){
    myScroll = $(window).scrollTop()  
});

$("#itemUnbind").click(function(){
    // here i need to remove the listener        
});

$("#itemBind").click(function(){
    // here i need to add listener again     
});

Thank you.

谢谢你。

回答by Andy E

You need to store the function in a variable and then use offto remove it:

您需要将该函数存储在一个变量中,然后使用off它来删除它:

var scrollHandler = function(){
    myScroll = $(window).scrollTop();
}

$("#itemBind").click(function(){
    $(window).scroll(scrollHandler);
}).click(); // .click() will execute this handler immediately

$("#itemUnbind").click(function(){
    $(window).off("scroll", scrollHandler);
});