[英]Smooth scroll to top of page
I have spent hours on this and being a newbie to JavaScript / JQuery I still don't know how to do the following:我已经花了几个小时在这方面,并且是 JavaScript / JQuery 的新手,我仍然不知道如何执行以下操作:
I have a "back to top" anchor link, in the footer of my pages, which links to the header.我在页面的页脚中有一个“回到顶部”的锚链接,它链接到 header。 I understand there is CSS code to make this a smooth scroll (slow) movement:我知道有 CSS 代码可以使这个平滑滚动(慢)运动:
html {
scroll-behavior: smooth;
}
But this does not work in Safari.但这在 Safari 中不起作用。
On the CSS Tricks website ( https://css-tricks.com/snippets/jquery/smooth-scrolling/ ) it says there is a JavaScript alternative to the above CSS: On the CSS Tricks website ( https://css-tricks.com/snippets/jquery/smooth-scrolling/ ) it says there is a JavaScript alternative to the above CSS:
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
But how or where do I add this to my link / page?但是如何或在哪里将其添加到我的链接/页面? I presume I would want top: 0,
我想我想要top: 0,
My HTML is this:我的 HTML 是这样的:
<header id="top">.... </header>
<footer>
<a href="#top"><img class="to-top" src="resources/arrow.svg"></a>
</footer>
UPDATE I've tried the following, but it doesn't work.更新我尝试了以下方法,但它不起作用。 Any ideas why?任何想法为什么?
<footer>
<a href="#top" onclick="window.scroll({ top: 0, behavior: 'smooth' })"><img class="to-top" src="resources/arrow.svg"></a>
</footer>
Use the onclick
-Event :使用onclick
事件:
<header id="top">....</header> <div style="background-color: red; height: 1200px"></div> <footer> <a style="cursor:pointer;" onclick="window.scroll({ 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>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.