如何使用jQuery滚动窗口
给定一个HTML文档,任务是在jQuery的帮助下滚动该文档。有两种方法可以滚动HTML文档的窗口,下面将讨论。
方法:
- 通过使用选择器选择文件。
- 使用scrollTop()或scrollTo()方法,将文档移动到该位置。
实例1:本实例使用scrollTop()方法滚动HTML文档。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to scroll window using jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style>
#body {
height: 1000px;
}
</style>
</head>
<body style = "text-align:center;" id = "body">
<h1 id = "h1" style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;">
</p>
<button onclick = "gfg_Run()">
Click here
<p id = "GFG_DOWN" style =
"font-size: 23px; font-weight: bold; color: green; ">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to scroll"
+ " the document.";
function gfg_Run() {
$(document).scrollTop(100);
el_down.innerHTML = "Position has been set.";
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。
例子2:这个例子使用scrollTo()方法滚动HTML文档。
<!DOCTYPE HTML>
<html>
<head>
<title>
How to scroll window using jQuery ?
</title>
<script src=
"https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js">
</script>
<style>
#body {
height: 1000px;
}
</style>
</head>
<body style = "text-align:center;" id = "body">
<h1 id = "h1" style = "color:green;" >
GeeksForGeeks
</h1>
<p id = "GFG_UP" style =
"font-size: 15px; font-weight: bold;">
</p>
<button onclick = "gfg_Run()">
Click here
<p id = "GFG_DOWN" style =
"font-size: 23px; font-weight: bold; color: green; ">
</p>
<script>
var el_up = document.getElementById("GFG_UP");
var el_down = document.getElementById("GFG_DOWN");
el_up.innerHTML = "Click on the button to scroll"
+ " the document.";
function gfg_Run() {
window.scrollTo(0, 100);
el_down.innerHTML = "Position has been set.";
}
</script>
</body>
</html>
输出:
- 在点击按钮之前。
- 点击该按钮后。