前言
返回顶部这个功能用jq实现,好容易实现,一个animate
配合scrollTo
就搞定了
今天我们来试试vue
封装一个原生js实现的返回顶部;
写起来够呛,借助github
,看了别人的gist
,稍微封装了下;
当然不是用scrollTo
直接调位那种,没有过渡效果怎么说得过去,还是捣鼓出来了。
效果图
实现思路
- 过渡用的是
requestAnimationFrame
,这货只支持IE10+,所以必须做兼容 - 滚动视图是
window.pageYOffset
,这货支持IE9+; - 为了让可控性更强,图标采用
iconfont
,具体瞅代码
你能学到什么?
- 学到一些页面计算相关的东东
- 动画API的一些知识
- Vue封装组件相关知识和生命周期和事件监听销毁相关知识的运用
实现功能
- 视图默认在
350
处显示返回顶部的按钮和图标 - 提示文字和颜色,在图标上下左右的自定义,字段都限制了格式和默认值
- 图标颜色和形状,大小的自定义,字段都限制了格式和默认值
- 过渡动效的自定义,用法:
scrollIt(0, 1500, 'easeInOutCubic', callback);
- 返回到视图的
point
,也就是滚动到哪里 - 过渡时间(ms级别)
- 一堆过渡效果,字符串格式,其实就是滚动的计算函数…
- 当然少不了默认参数了,除了
callback
- 返回到视图的
- 兼容性是
IE9+
,特意开了虚拟机去尝试
代码
scrollIt.js
--过渡滚动实现
export function scrollIt(
destination = 0,
duration = 200,
easing = "linear",
callback
) {
// define timing functions -- 过渡动效
let easings = {
// no easing, no acceleration
linear(t) {
return t;
},
// accelerating from zero velocity
easeInQuad(t) {
return t * t;
},
// decelerating to zero velocity
easeOutQuad(t) {
return t * (2 - t);
},
// acceleration until halfway, then deceleration
easeInOutQuad(t) {
return t < 0.5 ? 2 * t * t : -1 + (4 - 2 * t) * t;
},
// accelerating from zero velocity
easeInCubic(t) {
return t * t * t;
},
// decelerating to zero velocity
easeOutCubic(t) {
return --t * t * t + 1;
},
// acceleration until halfway, then deceleration
easeInOutCubic(t) {
return t < 0.5 ? 4 * t * t * t : (t - 1) * (2 * t - 2) * (2 * t - 2) + 1;
},
// accelerating from zero velocity
easeInQuart(t) {
return t * t * t * t;
},
// decelerating to zero velocity
easeOutQuart(t) {
return 1 - --t * t * t * t;
},
// acceleration until halfway, then deceleration
easeInOutQuart(t) {
return t < 0.5 ? 8 * t * t * t * t : 1 - 8