jQuery,如果滚动是一定数量的像素

编程入门 行业动态 更新时间:2024-10-24 16:29:16
本文介绍了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,如果滚动是一定数量的像素

本文发布于:2023-11-29 00:28:07,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1644566.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:像素   数量   jQuery   是一定

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!