html5锚点滚动

摘要

本文介绍了如何通过HTML5中的scrollIntoView方法实现平滑的锚点滚动效果。作者首先指出传统锚点滚动方式的两个问题:滚动动画不平滑且会改变URL。随后,作者提出使用scrollIntoView作为解决方案,并提供了具体代码示例。通过scrollIntoView方法,可以实现平滑滚动,同时避免URL的改变。该方法支持三个参数:behavior用于定义动画过渡效果,blockinline分别用于设置垂直和水平对齐方式。作者还提醒读者,Safari浏览器不支持scrollIntoView的参数配置,因此无法实现平滑滚动效果。本文适合前端开发者学习如何优化锚点滚动体验。



普通的锚点滚动方式是直来直去的,不太平滑,我们可以借助scrollIntoView实现平滑滚动。

原始方案

1
2
3
4
5
<div class="fixedbox">
    <a class="actiongithub" href="https://github.com/caibingcheng/rssblog" title="GitHub" target="_blank" rel="noopener noreffer me"></a>
    <a class="actiontop" href="#top-header"></a>
    <a class="actionbottom" href="#bottom-footer"></a>
</div>

一般会按照上述方案实现锚点滚动, 但是这种方案的问题有两点:

  1. 会改变url
  2. 滚动动画不平滑

scrollIntoView

采用scrollIntoView可以使用很少的代码实现平滑滚动, 并且不会改变url.

1
2
3
4
5
<div class="fixedbox">
    <a class="actiongithub" href="https://github.com/caibingcheng/rssblog" title="GitHub" target="_blank" rel="noopener noreffer me"></a>
    <a class="actiontop" onclick="javascript:document.getElementById('top-header').scrollIntoView({block: 'start', behavior: 'smooth', inline: 'center'})"></a>
    <a class="actionbottom" onclick="javascript:document.getElementById('bottom-footer').scrollIntoView({block: 'start', behavior: 'smooth', inline: 'center'})"></a>
</div>

scrollIntoView可以接收三个参数:

  • behavior: 定义动画过渡效果, “auto"或 “smooth” 之一. 默认为 “auto”.
  • block: 定义垂直方向的对齐, “start”, “center”, “end”, 或 “nearest"之一. 默认为 “start”.
  • inline: 定义水平方向的对齐, “start”, “center”, “end”, 或 “nearest"之一. 默认为 “nearest”.

注意: Safari桌面和移动端都不支持scrollIntoView参数, 仅可以使用默认配置, 这时候是没有平滑滚动效果的.