Jquery if scroll is a certain amount of pixels

前端 未结 1 518
轮回少年
轮回少年 2020-12-13 09:39

Is there a built in jQuery function to determine the length of a scroll?

I\'m trying to write a function that will add a class to a div if the user has scrolled 50 p

1条回答
  •  一生所求
    2020-12-13 10:22

    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);
    });
    

    See http://api.jquery.com/scrollTop/.

    Note that it is very inefficient to use scroll event handlers.

    0 讨论(0)
提交回复
热议问题