Jquery 如果滚动是一定数量的像素
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8148310/
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 if scroll is a certain amount of pixels
提问by Ryan
Is there a built in jQuery function to determine the length of a scroll?
是否有内置的 jQuery 函数来确定滚动的长度?
I'm trying to write a function that will add a class to a div if the user has scrolled 50 pixels from the top.
我正在尝试编写一个函数,如果用户从顶部滚动了 50 个像素,它将向 div 添加一个类。
So the code will look like this:
所以代码看起来像这样:
if(userHasScrolled) {
$('#myDiv').addClass('hasScrolled');
}
回答by Mathias Bynens
You can check $(document).scrollTop()
inside of a scroll handler:
您可以检查$(document).scrollTop()
滚动处理程序的内部:
var $document = $(document),
$element = $('#some-element'),
className = 'hasScrolled';
$document.scroll(function() {
if ($document.scrollTop() >= 50) {
// user scrolled 50 pixels or more;
// do stuff
$element.addClass(className);
} else {
$element.removeClass(className);
}
});
If adding the class name is all you want (no other actions needed), this could be shortened to:
如果您只需要添加类名(不需要其他操作),则可以缩短为:
var $document = $(document),
$element = $('#some-element'),
className = 'hasScrolled';
$document.scroll(function() {
$element.toggleClass(className, $document.scrollTop() >= 50);
});
See http://api.jquery.com/scrollTop/.
请参阅http://api.jquery.com/scrollTop/。
Note that it is very inefficient to use scroll
event handlers.
请注意,使用scroll
事件处理程序是非常低效的。