javascript jQuery - 滚动功能不断触发:请只触发一次
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16782753/
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
jQuery - Scroll Function Keeps Triggering: Only Once Please
提问by tehSUPERADMIN
I have the following jQuery function which triggers aTestEvent()
when the user scrolls horizontally past 500 pixels:
我有以下 jQuery 函数,aTestEvent()
当用户水平滚动超过 500 像素时触发:
jQuery(document).scroll(function(){
if(jQuery(this).scrollLeft() >= 500){
aTestEvent();
}});
Here's the issue: I only want aTestEvent()
to be triggered once! However, every time the user scrolls back to the beginning of the page and then again past 500 pixels, aTestEvent()
is triggered again.
问题是:我只想aTestEvent()
被触发一次!但是,每次用户滚动回到页面的开头,然后再次超过 500 像素时,aTestEvent()
都会再次触发。
How can we adjust the above code so that the trigger only occurs for the first timethe user scrolls past 500 pixels?
我们如何调整上面的代码,使得触发器只在用户第一次滚动超过 500 像素时发生?
回答by undefined
You can use on
and off
methods:
您可以使用on
和off
方法:
$(document).on('scroll', function() {
if( $(this).scrollLeft() >= 500 ) {
$(document).off('scroll');
aTestEvent();
}
});
Please Note: This code snippet could "off" all the scroll event available on a particular page but to scroll off only intended scroll handler without disturbing other scroll handlers, we can use a namespace. Namespaces are similar to CSS classes in that they are not hierarchical; only one name needs to match.
请注意:此代码片段可以“关闭”特定页面上可用的所有滚动事件,但要仅滚动关闭预期的滚动处理程序而不干扰其他滚动处理程序,我们可以使用命名空间。命名空间与 CSS 类相似,因为它们没有层次结构;只需要匹配一个名称。
$(document).on('name1.scroll', function() {
if( $(this).scrollLeft() >= 500 ) {
$(document).off('name1.scroll');
aTestEvent();
}
});