本期教程介绍一下怎样用一行代码实现网页内部跳转链接的平滑滚动,同时介绍一个兼容性更好的神器Smooth-scroll。

This tutorial introduces how to use a single line of code to achieve smooth scrolling, and introduces a more compatible artifact: Smooth-scroll.

目录 / LIST


# 修改style.css | Modify style.css

  • 实现平滑滚动最简单的一种方法,一行代码就可以实现,只需要在Hugo主题目录下static/assetsstyle.css文件中直接加入如下代码即可。
  • The easiest way is adding a single line of code directly to the style.css file in the static/assets directory of the Hugo theme.
html, body { scroll-behavior:smooth; }
  • 但是这种方法兼容性不好,比如Safari浏览器就不支持,因此需要寻找一种兼容性更好的方案。
  • However, this method is not compatible, such as Safari browser, so we need to find a more compatible solution.
x

# 下载Smooth-scroll | Downloading

  • 推荐使用Smooth-scroll这个轻量级脚本来实现平滑滚动,首先需要在GitHub项目里的releases里下载最新脚本。
  • It is recommended to use the lightweight script Smooth-scroll for smooth scrolling. First you need to download the latest script in releases in the GitHub project.

Releases · cferdinandi/smooth-scroll · GitHub

  • src/js/smooth-scroll/目录下解压smooth-scroll.js文件到Hugo主题文件夹下的static/assets目录下即可。
  • Unzip the smooth-scroll.js file in the src/js/smooth-scroll/ directory to the static/assets directory under the Hugo theme folder.

# 配置Smooth-scroll | Configurations

  • 回到Hugo主题文件夹下的layoust/_default文件夹下的single.html文件,把下面的代码拷进到{{ define "main" }}之后。再去SSH里Hugo一下就搞定啦。
  • Go back to the single.html file in the layoust/_default folder under the Hugo theme folder and copy the following code after {{ define "main" }}.
<script src="{{ "assets/smooth-scroll.js" | absURL }}"></script>
<script>var scroll = new SmoothScroll('a[href*="#"]', { speed: 200 });</script>
  • 可以通过修改speed调节滚动的速度,默认200。想了解更多,点击下方项目地址。
  • You can adjust the scrolling speed by modifying speed, which defaults to 200. To find out more, click on the address below.

GitHub - cferdinandi/smooth-scroll: A lightweight script to animate scrolling to anchor links.

 
• 本文作者 | Author info >> 冰川大魔王
• 来源链接 | Source link >> 用Smooth-scroll实现平滑滚动 | It makes scrolling smooth & natural
• 发表评论 | Make comments >>