Jquery method to determine the direction of the scroll event: use the [scrollTop()] method to set or return the vertical scroll bar position of the selected element, the syntax is [$(selector).scrollTop(position)].
The operating environment of this tutorial: Windows 7 system, jquery version 3.2.1. This method is suitable for all brands of computers.
jquery's method of determining the direction of a scrolling event:
In jQuery, you can use the scrollTop() method to determine the direction of a scrolling event. The scrollTop() method is used to set or Returns the vertical scroll bar position of the selected element. Using this method, we can determine the scroll direction.
<strong>jQuery scrollTop()</strong>
Method
scrollTop() method sets or returns the vertical scroll bar position of the selected element.
Tip: When the scroll bar is at the top, the position is 0.
Syntax:
$(selector).scrollTop(position)
Parameters: This method accepts a single parameter position, which is optional. It is used to specify the vertical scroll bar position in pixels.
Return value: Returns the vertical position of the scroll bar of the selected element.
Example:
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <style> html,body { height: 300% } div { position: fixed; padding-left: 10px; padding-top: 30px; height: 10%; width: 35%; font-weight: bold; border: 2px solid red; } </style> </head> <body> <div></div> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script> var position = $(window).scrollTop(); $(window).scroll(function() { var scroll = $(window).scrollTop(); if(scroll > position) { console.log('scrollDown'); $('div').text('向下滚动'); } else { console.log('scrollUp'); $('div').text('向上滚动'); } position = scroll; }); </script> </body> </html>
Related free learning recommendations:JavaScript(Video)
The above is the detailed content of How to determine the direction of scroll event in jquery. For more information, please follow other related articles on the PHP Chinese website!