顺畅滚动到顶部 [英] smooth scroll to top

查看:103
本文介绍了顺畅滚动到顶部的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经在几个小时内搜索了这个,我没有解决方案。我想要一个平滑的滚动到页面顶部。我已经有平滑的滚动来分隔页面中的锚点,并附加到我的网站上的 .js 文件,但我不能使用锚点作为顶部,因为我正在使用模板来自免费托管网站,内置页面构建工具,不允许我在正文区域上方进行编辑。

I've bean searching for this for a few hours now and I have no solution. I want a smooth scroll to the top of the page. I already have smooth scrolling to separate anchors in the page with a .js file attatched to my site but I cannot use an anchor for the top, because I'm using a template from a free hosting site with built in page building tools that do not allow me to edit above the body area.

这里是我顺利滚动的地方。我一直在尝试设置平滑滚动到元素 - 没有jquery插件但我不知道如何在无数次尝试之后安排它。我还使用了 window.scrollTo(0,0); 但它立即滚动。谢谢!

Here's where I got the smooth scrolling. I've been trying to set up "smoothly-scroll-to-an-element-without-a-jquery-plugin" but I have no idea how to arrange it obviously after countless attempts. I've also used window.scrollTo(0, 0); but it scrolls instantly. Thanks!

此外:
http:// jsfiddle.net/WFd3V/ - 代码可能是标签 class =smoothScroll,因为我的其他元素使用它,但我不知道如何将它与 href =javascript:window.scrollTo(0,0);混合,或者将页面置于顶部而没有锚点的任何其他内容。

In addition: http://jsfiddle.net/WFd3V/ - the code would probably be the tag class="smoothScroll" since my other element uses that, but I don't know how to mix it with the href="javascript:window.scrollTo(0,0);" , or anything else that would bring the page to the top without an anchor.

推荐答案

以下是我用ES6实施的建议

Here is my proposal implemented with ES6

const scrollToTop = () => {
  const c = document.documentElement.scrollTop || document.body.scrollTop;
  if (c > 0) {
    window.requestAnimationFrame(scrollToTop);
    window.scrollTo(0, c - c / 8);
  }
};
scrollToTop();

提示:对于较慢的滚动动作,增加硬编码的数量 8 。数字越大 - 滚动越平滑/越慢。

Tip: for slower motion of the scrolling, increase the hardcoded number 8. The bigger the number - the smoother/slower the scrolling.

这篇关于顺畅滚动到顶部的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆