如何在jQuery中运行滚动事件的代码
在这篇文章中,我们将讨论如何使用jQuery在用户滚动内容时运行代码。为了在滚动的内容中运行代码,我们使用了scroll()方法。scroll()方法是用来在用户滚动指定的元素时运行代码的。
语法:
$(selector).scroll(function)
参数:该方法接受单参数函数,这是可选的。它用于指定当滚动事件被触发时要运行的函数。
方法:在下面的例子中,我们创建了一个包含元素内容的div元素,我们在div元素上使用了一些CSS样式。我们为滚动添加了一个overflow-y属性,使内容可以滚动。当用户滚动div内容时,jQuery scroll()方法被调用,该方法包含css()方法,在div元素上应用一些CSS样式。
示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content=
"width=device-width, initial-scale=1.0">
<title>
How to run a code on scroll event using jQuery?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js">
</script>
<style>
h1,
h3 {
text-align: center;
}
.GFG {
width: 350px;
height: 150px;
border: 1px solid black;
overflow-x: hidden;
overflow-y: scroll;
text-align: justify;
display: flex;
margin: 0 auto;
}
</style>
</head>
<body>
<h1 style="color: green;">
GeeksforGeeks
</h1>
<h3>
How to run a code on scroll event using jQuery?
</h3>
<div class="GFG">
HTML stands for HyperText Markup Language. It
is used to design web pages using a markup
language. HTML is the combination of Hypertext
and Markup language. Hypertext defines the link
between the web pages. A markup language is
used to define the text document within tag
which defines the structure of web pages. This
language is used to annotate (make notes for
the computer) text so that a machine can
understand it and manipulate text accordingly.
Most markup languages (e.g. HTML) are
human-readable. The language uses tags to
define what manipulation has to be done on
the text.
</div>
<script>
(document).ready(function () {
(".GFG").scroll(function () {
$(".GFG").css({
"fontSize": "18px",
"color": "green"
})
});
});
</script>
</body>
</html>
输出: