乐趣区

Scrollbar平滑滚到指定位置

背景
近期项目需求实现同一页面内进行导航跳转。
一开始想到的是通过 <a> 标签描点定位,但是跳转效果不好,没有过渡的动画。
后来试了 scrollIntoView 和 scroll-behavior: smooth,一方面浏览器兼容性不好,另一方面无法控制过渡时间,当页面内容很多时,跳转太慢了。
于是自己封装了一个跳转函数,支持立刻跳转、线性过渡、先快后慢(缓动)三种跳转方式,具体如下:

演示
https://theoxiong.github.io/s…

安装方法
$ npm install scroll-ease-efficient
使用
// 支持 CommonJs/ES6/Script 三种引入
// 1. CommonJs
const {scrollTo} = require(‘scroll-ease-efficient’)
// 2. ES6
import {scrollTo} from ‘scroll-ease-efficient’
// 3. Script
<script type=”text/javascript” src=”scroll-ease-efficient/index.js”></script>

// scrollable element
let scrollEle = document.getElementById(‘id’)

// 基本用法
scrollTo(scrollEle, 500)

// 指定过渡时间(单位 ms)
scrollTo(scrollEle, 500, { duration: 500})

// 指定过渡动画效果, 支持 ’gradually’/’liner’/’instant’
scrollTo(scrollEle, 500, { timingFunction: ‘gradually’})

// 指定过渡时间和动画效果
scrollTo(scrollEle, 500, { timingFunction: ‘liner’, duration: 500})

// 指定缓动因子, 只对 ’gradually’ 方式有效
scrollTo(scrollEle, 500, { timingFunction: ‘gradually’, factor: 6})
函数说明
function scrollTo (ele, pos, [options])

ele < Dom> target scrollable element

pos <Number> specified the position which scroll to

options <Object>

timingFunction <String> specify velocity curve of scrolling, default value is ‘linear’

duration <Number> specify time of scrolling, default value is 1000

factor <Number> specify the factor of gradually scrolling, it is only for gradually mode, should less then 100, and more then 1

退出移动版