滚动元素到可视区

156 阅读1分钟

概述

在项目里面,肯定会遇到元素跳转到可视区的需求,比较常见的就像百度搜索的时候,根据目录节点跳转指定章节到可视区,如下:

image.png

实现方案

地址哈希

点击对应元素,直接会在地址栏上拼接上元素hash值

image.png

//a标签herf绑定hash id
<a href="#section-id">跳转到章节</a>
//绑定锚点hash id
<div id="section-id">目标内容</div>

好处

  • 直接地址分享给别人,能直接定位到指定元素为止

缺点

  • 无法实现更加精准的定位,只能默认顶部对齐(如:底部对齐、中间对齐、自定义位置对齐)
  • 如果spa应用使用hash路由,可能会出现些冲突,需要额外处理

js跳转

可通过如下api方式操作,更加灵活

1. scrollIntoView()

element.scrollIntoView({
  behavior: 'smooth', // 可选: 'auto' 或 'smooth'
  block: 'nearest',   // 可选: 'start', 'center', 'end', 'nearest'
  inline: 'nearest'   // 可选: 'start', 'center', 'end', 'nearest'
});

2. scrollTo() 或 scroll()

// 滚动到特定位置
window.scrollTo({
  top: element.offsetTop,
  behavior: 'smooth'
});

// 或者使用元素滚动
container.scroll({
  top: element.offsetTop - container.offsetTop,
  behavior: 'smooth'
});

好处

  • 自定义程度更好,可根据自己实际需求进行处理

缺点

  • 对外分享需要额外处理定位(如通过路由参数)