锚点平滑滚动之scrollIntoView
Posted Rand Tsui
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了锚点平滑滚动之scrollIntoView相关的知识,希望对你有一定的参考价值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>锚点平滑滚动</title>
<style>
#d1{
background-color: #FFFCF0;
height: 400px;
}
#d2{
background-color: #44AA11;
height: 700px;
}
#d3{
background-color: #C34914;
height: 300px;
}
#d4{
background-color: #f43a89;
height: 1500px;
}
#d5{
background-color: #13f683;
height: 500px;
}
#d6{
background-color: #f43a89;
height: 700px;
}
.links{
position: fixed;
right: 30px;
top: 0;
}
.links > *{
display: block;
}
</style>
</head>
<body>
<div id="d1">d1</div>
<div id="d2">d2</div>
<div id="d3">d3</div>
<div id="d4">d4</div>
<div id="d5">d5</div>
<div id="d6">d6</div>
<div class="links">
<a href="#d1">d1</a>
<a href="#d2">d2</a>
<a href="#d3">d3</a>
<a href="#d4">d4</a>
<a href="#d5">d5</a>
<a href="#d6">d6</a>
</div>
<script>
document.querySelectorAll('a[href^="#"]').forEach(item => {
item.addEventListener('click', e => {
let target = document.querySelector(item.getAttribute('href'));
target.scrollIntoView({ behavior: 'smooth' });
e.preventDefault()
})
});
</script>
</body>
</html>
以上是关于锚点平滑滚动之scrollIntoView的主要内容,如果未能解决你的问题,请参考以下文章
scrollIntoView+锚点两种方式实现页面的平滑滚动,长页面分页