平滑滚动到页面顶部

use*_*837 2 html javascript css

我花了几个小时在这上面,作为 JavaScript / JQuery 的新手,我仍然不知道如何执行以下操作:

我的页面页脚中有一个“返回顶部”锚链接,它链接到页眉。我知道有 CSS 代码可以使其平滑滚动(缓慢)移动:

html {
  scroll-behavior: smooth;
}
Run Code Online (Sandbox Code Playgroud)

但这在 Safari 中不起作用。

在 CSS Tricks 网站(https://css-tricks.com/snippets/jquery/smooth-scrolling/)上,它说有一个 JavaScript 可以替代上述 CSS:

window.scroll({
  top: 2500, 
  left: 0, 
  behavior: 'smooth'
});
Run Code Online (Sandbox Code Playgroud)

但是如何或在哪里将其添加到我的链接/页面?我想我会想要top: 0,

我的 HTML 是这样的:

<header id="top">.... </header>

<footer>
<a href="#top"><img class="to-top" src="resources/arrow.svg"></a>
</footer>
Run Code Online (Sandbox Code Playgroud)

更新我已经尝试过以下方法,但它不起作用。有什么想法吗?

<footer>
    <a href="#top" onclick="window.scroll({ top: 0, behavior: 'smooth' })"><img class="to-top" src="resources/arrow.svg"></a>
</footer>
Run Code Online (Sandbox Code Playgroud)

Lar*_*ger 8

使用onclick-Event

<header id="top">....</header>
<div style="background-color: red; height: 1200px"></div>
<footer>
  <a style="cursor:pointer;" onclick="window.scrollTo({ top: 0, behavior: 'smooth' })"><img class="to-top" src="https://upload.wikimedia.org/wikipedia/commons/thumb/d/d6/Feather-arrows-arrow-up.svg/24px-Feather-arrows-arrow-up.svg.png"></a>
</footer>
Run Code Online (Sandbox Code Playgroud)