Jquery 如果滚动是一定数量的像素 [英] Jquery if scroll is a certain amount of pixels
本文介绍了Jquery 如果滚动是一定数量的像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
是否有内置的 jQuery 函数来确定滚动的长度?
Is there a built in jQuery function to determine the length of a scroll?
我正在尝试编写一个函数,如果用户从顶部滚动 50 个像素,该函数将向 div 添加一个类.
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.
所以代码看起来像这样:
So the code will look like this:
if(userHasScrolled) {
$('#myDiv').addClass('hasScrolled');
}
推荐答案
您可以在滚动处理程序中检查 $(document).scrollTop()
:
You can check $(document).scrollTop()
inside of a scroll handler:
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);
});
参见 http://api.jquery.com/scrollTop/.
请注意,使用 scroll
事件处理程序是非常低效的.
Note that it is very inefficient to use scroll
event handlers.
这篇关于Jquery 如果滚动是一定数量的像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文