本文介绍了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.
所以代码将如下所示:
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); });请参见 api.jquery/scrollTop/.
请注意,使用scroll事件处理程序的效率非常低.
Note that it is very inefficient to use scroll event handlers.
更多推荐
jQuery,如果滚动是一定数量的像素
发布评论