使用JavaScript或jQuery滚动到页面顶部
一个可滚动的页面可以用2种方法滚动到顶部。
方法1:使用 window.scrollTo()
窗口接口的scrollTo()方法可以用来滚动到页面上的一个指定位置。它接受两个参数,即要滚动到的页面的x和y坐标。传递两个参数为0,将滚动页面到最上面和最左边的位置。
语法:
window.scrollTo(x-coordinate, y-coordinate)
示例:
<!DOCTYPE html>
<html>
<head>
<title>
Scroll to the top of the
page using JavaScript/jQuery?
</title>
<style>
.scroll {
height: 1000px;
background-color: lightgreen;
}
</style>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>Scroll to the top of the page
using JavaScript/jQuery?</b>
<p>Click on the button below to
scroll to the top of the page.</p>
<p class="scroll">GeeksforGeeks is a
computer science portal. This is a
large scrollable area.</p>
<button onclick="scrollToTop()">
Click to scroll to top
</button>
<script>
function scrollToTop() {
window.scrollTo(0, 0);
}
</script>
</body>
</html>
输出:
方法2:使用 crollTop( 在jQuery中:
在jQuery中,scrollTo()方法是用来设置或返回所选元素的垂直滚动条位置。这个行为可以通过在window属性上应用这个方法来滚动到页面的顶部。将位置参数设置为0可以将页面滚动到顶部。
语法:
$(window).scrollTop(position);
示例:
<!DOCTYPE html>
<html>
<head>
<title>
Scroll to the top of the
page using JavaScript/jQuery?
</title>
<style>
.scroll {
height: 1000px;
background-color: lightgreen;
}
</style>
</head>
<body>
<h1 style="color: green">
GeeksforGeeks
</h1>
<b>
Scroll to the top of the page
using JavaScript/jQuery?
</b>
<p>
Click on the button below to
scroll to the top of the page.
</p>
<p class="scroll">
GeeksforGeeks is a computer
science portal.
This is a large scrollable area.
</p>
<button onclick="scrollToTop()">
Click to scroll to top
</button>
<script src="https://code.jquery.com/jquery-3.3.1.min.js">
</script>
<script>
function scrollToTop() {
$(window).scrollTop(0);
}
</script>
</body>
</html>
输出:
JavaScript在网页开发中最为出名,但它也被用于各种非浏览器环境。你可以通过学习这个JavaScript教程和JavaScript实例,从基础开始学习JavaScript。
jQuery是一个开源的JavaScript库,它简化了HTML/CSS文档之间的交互,它因其 “少写多做 “的理念而广为人知。你可以通过学习这个jQuery教程和jQuery实例,从基础开始学习jQuery。