如何删除仅在滚动事件中执行的特殊指令?
例如我得到了这段代码:
$(document).scroll(function(){
// instructions
});
而且我希望“说明”仅在显示我的一个 div 时起作用(display:block)。 实际上,当我隐藏 div 时,我不再希望在滚动时应用说明...
由于简单的“if(mySpecialVar==true){//instructions}”,我可以创建一个函数来收集我的指令并使它们得以执行。像这样:
$(document).scroll(function(){
if(mySpecialVar==true){//instructions}
});
这样,我可以在隐藏或显示 div 时修改 mySpecialVar。但我什至不希望浏览器在不必执行指令(为了最大优化)时做出这个简单的条件。
有什么想法吗? :)
最佳答案
您可以将函数保存在变量中,将其绑定(bind)到事件,然后像这样将其删除:
var the_function = function(){/*instructions*/};
在显示 div 的代码中:
$(document).on("scroll", the_function);//Attach the event
在隐藏 div 的代码中:
$(document).off("scroll", the_function);//Remove the event
关于javascript - 如何删除附加到滚动事件的行为?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18722006/