返回顶部按钮行为

时间:2021-06-14 06:36:24

标签: javascript html

您好,我想弄清楚我可以使用什么来让我的“返回顶部”按钮平滑滚动。我不想使用常规的“滚动行为:平滑;”因为我正在使用动画 css 库来利用其他动画功能,例如“淡入淡出”。说了这么多,我到底要在下面的代码中添加什么,才能让我的“返回顶部”按钮平滑滚动。

//Get the button
var mybutton = document.getElementById("btnToTheTop");

// When the user scrolls down 150px from the top of the document, show the button
window.onscroll = function() { scrollFunction() };

function scrollFunction() {
    if (document.body.scrollTop > 150 || document.documentElement.scrollTop > 150) {
        mybutton.style.display = "block";
    } else {
        mybutton.style.display = "none";
    }
}

// When the user clicks on the button, scroll to the top of the document
function topFunction() {
    document.body.scrollTop = 0;
    document.documentElement.scrollTop = 0;
}

1 个答案:

答案 0 :(得分:0)

使用scrollIntoView()

  const smoothScroll = () => {
    const el = document.querySelector("btnToTheTop");
    el.scrollIntoView({ block: "center", behavior: "smooth" });
  };

并将其放入 onClick

相关问题