第一种方法:添加css样式scroll-behavior: smooth;
为一个滚动框指定滚动行为,smooth指的是平滑滚动,一般用于根标签,让视窗内的锚点跳转更平滑。
第二种方法:利用元素的属性scrollTo、scrollIntoView进行滚动设置
滚动到顶部
window.scrollTo({top: 0, left: 0, behavior: "smooth"})
滚动到底部
window.scrollTo({ top: document.documentElement.offsetHeight, left: 0, behavior: "smooth", })
滚动到该元素的可视区域
element.scrollIntoView({ behavior: "smooth", })
举例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,body {
/* 方法一 */
scroll-behavior: smooth;
}
.header {
width: 100%;
height: 100px;
background-color: lightblue;
}
.header>a {
width: 100px;
height: 80px;
line-height: 80px;
color: red;
}
.main {
width: 100%;
background-color: rgb(29, 29, 92);
/* 方法一 */
/* scroll-behavior: smooth; */
}
.main>a {
display: block;
width: 100%;
height: 1000px;
color: #fff;
}
.footer {
width: 100%;
height: 80px;
background-color: rgb(3, 3, 26);
}
</style>
</head>
<body>
<!-- 平滑滚动样式 -->
<header class="header">
<a href="#a1">1</a>
<a href="#a2">2</a>
<!-- <a href="#a3">3</a> -->
<a onclick="smoothScroll(document.getElementById('a3'))">3</a>
<button onclick="test()">测试</button>
<button onclick="scrollToBottom()">滚到底</button>
</header>
<main class="main">
<a href="" id="a1">1</a>
<a href="" id="a2">2</a>
<a href="" id="a3">3</a>
</main>
<footer class="footer">
<button onclick="scrollToTop()">滚到顶</button>
</footer>
<script>
// 方法二
// 补充页面滚动顶部
const scrollToTop = () => {
window.scrollTo({ top: 0, left: 0, behavior: "smooth" });
}
// 页面滚到底部
const scrollToBottom = () => {
window.scrollTo({
top: document.documentElement.offsetHeight,
left: 0,
behavior: "smooth",
})
}
// 页面滚动到可见区域
const smoothScroll = (element) => {
element.scrollIntoView({
behavior: "smooth",
})
}
//测试
function test() {
const a3 = document.querySelector("#a3");
a3.scrollIntoView({
behavior: 'smooth'
});
}
</script>
</body>
</html>