如何使返回顶部锚链接平滑滚动



我正试图使回到顶部按钮点击是平滑滚动,但我卡住了。目前这段代码的工作,但它不顺利滚动到页面的顶部…有人能帮我一下吗?

<a id="BackToTop" href="#" title="Back to the top" class="back-to-top hide">
<span>⌃</span>
</a>
<style>
.back-to-top {
position: fixed;
bottom: 20px;
right: 25px;
color: #999;
background-color: #243066;
z-index: 60000;  
}
.back-to-top span{
height: 47px;
}
.hide {
display: none!important;
}
.back-to-top:hover {
box-shadow: 1px 1px 25px #9e9e9e;
}
</style>
<script>
(function() {
function trackScroll() {
var scrolled = window.pageYOffset;
var coords = 300;
if (scrolled > coords) {
goTopBtn.classList.remove('hide');
}
if (scrolled < coords) {
goTopBtn.classList.add('hide');
}
}
function backToTop() {
if (window.pageYOffset > 0) {
window.scrollBy(0, -80);
setTimeout(backToTop, 0);
}
}
var goTopBtn = document.querySelector('.back-to-top');
window.addEventListener('scroll', trackScroll);
goTopBtn.addEventListener('click', backToTop);
})();
</script>

现代浏览器(除了IE)都支持窗口对象的scrollTo方法,您可以将平滑滚动行为传递给:

window.scrollTo({ top: 0, left: 0, behavior: 'smooth'});

这也有变化,如element.scrollIntoView()

您可以使用

document.getElementById('id').scrollIntoView({
behavior: 'smooth'
});
document
.getElementById("id")
.scrollIntoView({ block: "start", behavior: "smooth" });
body{
scroll-behaviour: smooth;
}

最新更新