Home > Web Front-end > JS Tutorial > body text

How to determine the direction of scroll event in jquery

coldplay.xixi
Release: 2020-11-30 10:57:40
Original
1940 people have browsed it

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)].

How to determine the direction of scroll event in jquery

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)
Copy after login

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(&#39;scrollDown&#39;);
$(&#39;div&#39;).text(&#39;向下滚动&#39;);
} else {
console.log(&#39;scrollUp&#39;);
$(&#39;div&#39;).text(&#39;向上滚动&#39;);
}
position = scroll;
});
</script>
</body>
</html>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!