better-scroll 源码分析
我写该文章,主要是想结合代码探究 better-scroll 是如何处理下列操作的。该过程如下图,用文字描述为:手指触摸屏幕,向上快速滑动,最后在手指离开屏幕后,内容获得动量继续滚动,若内容滚动超越顶部边界会回弹。
我们从整体开始一步一步来探究。better-scroll 包装了一个 BScroll 类以提供功能,我们可以在 better-scroll/src/index.js 文件中看到,它的构造器中传入两个参数 el 和 options。在构造函数中,比较重要的是执行_init(el, options)方法,如下所示。
function BScroll(el, options) {
// ...
this._init(el, options)
}
_init(el, options)方法在better-scroll/src/scroll/init.js文件中定义,相关代码如下。
BScroll.prototype._init = function (el, options) {
// ... this._addDOMEvents() // 添加事件处理函数 this._initExtFeatures() // 初始化特性操作,如下拉刷新 this._watchTransition() // ...
}
因为如何实现特性操作并不是我的主要目的,所以 _initExtFeatures() 我们忽略掉。先来看一下 _watchTransition() 方法,该方法的代码如下。
BScroll.prototype._watchTransition = function () {
// ...
let me = this
let isInTransition = false
Object.defineProperty(this, 'isInTransition', {
get () {
return isInTransition
},
set (newVal) {
isInTransition = newVal
let el = me.scroller.children.length ? me.scroller.children : [me.scroller]
let pointerEvents = (isTransition && !me.pulling) ? 'none' : 'auto'
for (let i = 0; i < le.length; i++) {
el[i].style.pointerEvents = pointerEvents
}
}
})
}
此方法的功能主要是为BScroll类的实例,使用Object.defineProperty()增加一个isInTransition属性。当将该属性赋值为true时,将会使滚动元素下的子元素的pointerEvents样式属性赋值为none,以此子元素无法点击。该处理将用在元素滚动等状态时,用户的触摸的期望应该触发的是滚动停止等操作,而不是子元素点击事件。
_addDOMEvents()方法主要用来绑定事件处理程序,其中在源码中还定义了_removeDOMEvents()方法,它们都会调用_handleDOMEvents(eventOperation)方法。不同的是,_addDOMEvents中eventOperation = addEvent,_removeDOMEvents中eventOperation = removeEvent。
addEvent和removeEvent只是包装了DOM 2级事件处理方法。
function addEvent(el, type, fn, capture) {
el.addEventListener(type, fn, {passive: false, capture: !!capture})
}
function removeEvent(el, type, fn, capture) {
el.removeEventListener(type, fn, {passive: false, capture: !!capture})
}
看一下_handleDOMEvents(eventOperation)方法的源码,可以看到eventOperation方法像下面这样调用。
BScroll.prototype._handleDOMEvents = function (eventOperation) {
// ...
eventOperation(window, 'resize', this) // ...
}
可以看到,参数fn被传入的是BScroll类实例的this指针,而不是一个方法。其实是在BScroll类中定义了一个handleEvent方法根据事件类型来处理所有事件。这是HTML5的一个特性,具体介绍可以参照该博文 http://www.ayqy.net/blog/handleevent%E4%B8%8Eaddeventlistener/
handleEvent方法的源码如下。
BScroll.prototype.handleEvent = function (e) {
switch (e.type) {
case 'touchstart':
case 'mousedown':
this._start(e)
break
case 'touchmove':
case 'mousemove':
this._move(e)
break
case 'touchend':
case 'mouseup':
case 'touchcancel':
case 'mousecancel':
this._end(e)
break
case 'orientationchange':
case 'resize':
this._resize()
break
case 'transitionend':
case 'webkitTransitionEnd':
case 'oTransitionEnd':
case 'MSTransitionEnd':
this._transitionEnd(e)
break
case 'click':
if (this.enabled && !e._constructed) {
if (!preventDefaultException(e.target, this.options.preventDefaultException)) {
e.preventDefault()
e.stopPropagation()
}
}
break
case 'wheel':
case 'DOMMouseScroll':
case 'mousewheel':
this._onMouseWheel(e)
break
}
}
最终处理事件的方法落在_start、_move、_end、_transitionEnd。即,手指触摸时 _start 函数进行处理,手指移动时 _move 函数进行处理,手指离开时 _end 函数进行处理,移动到最远距离后 _transitionEnd 函数处理以进行回弹。
_start 函数中记录了 e.touches[0].pageX 与 e.touches[0].pageY。
let point = e.touches ? e.touches[0] : e
this.startX = this.x
this.startY = this.y
this.absStartX = this.x
this.absStartY = this.y
this.pointX = point.pageX
this.pointY = point.pageY
先来看一下 _move 中的主要代码。
let point = e.touches ? e.touches[0] : e
let deltaX = point.pageX - this.pointX
let deltaY = point.pageY - this.pointY
this.pointX = point.pageXthis.pointY = point.pageY
this.distX += deltaXthis.distY += deltaY let absDistX = Math.abs(this.distX)
let absDistY = Math.abs(this.distY) let timestamp = getNow()
// 我们需要移动最小的距离(单位px)为momentumLimitDistance
if (timestamp - this.endTime > this.options.momentumLimitTime && (absDistY < this.options.momentumLimitDistance && absDistX < this.options.momentumLimitDistance)) {
return
} let newX = this.x + deltaX
let newY = this.y + deltaY
if (newX > 0 || newX < this.maxScrollX) {
if (this.options.bounce) {
newX = this.x + deltaX / 3
} else {
newX = newX > 0 ? 0 : this.maxScrollX
}
}if (newY > 0 || newY < this.maxScrollY) {
if (this.options.bounce) {
newY = this.y + deltaY / 3
} else {
newY = newY > 0 ? 0 : this.maxScrollY
}
}
this._translate(newX, newY)
if (timestamp - this.startTime > this.options.momentumLimitTime) {
this.startTime = timestamp
this.startX = this.x
this.startY = this.y
}
为了防止用户触摸时的抖动,要求移动的最小距离要大于 momentumLimitDistance。
接着处理移动边缘,若移动到上下边缘,那么内容移动的距离将为手指移动距离的1/3,使用户产生拥有阻力的感觉。
接着使用 _translate(newX, newY) 函数改变内容块的 transition css属性来产生移动效果。
接下来的代码的作用是为了获取手指离开屏幕时的瞬时速度,我们都知道速度等于距离/时间,当采样的时间越小,计算出的速度更接近瞬时速度。better-scroll 的采样时间要求小于 momentumLimitTime。
最后在 _end 函数中是如何计算出动量的。
// start momentum animation if needed
if (this.options.momentum && duration < this.options.momentumLimitTime && (absDistY > this.options.momentumLimitDistance || absDistX > this.options.momentumLimitDistance)) {
let momentumX = this.hasHorizontalScroll ? momentum(this.x, this.startX, duration, this.maxScrollX, this.options.bounce ? this.wrapperWidth : 0, this.options)
: {destination: newX, duration: 0}
let momentumY = this.hasVerticalScroll ? momentum(this.y, this.startY, duration, this.maxScrollY, this.options.bounce ? this.wrapperHeight : 0, this.options)
: {destination: newY, duration: 0}
newX = momentumX.destination
newY = momentumY.destination
time = Math.max(momentumX.duration, momentumY.duration)
this.isInTransition = true
}
使用 momentum 函数来计算动量,我们接下来看一下 momentu 函数,在 better-scroll/src/util/momentum.js 文件中。
export function momentum(current, start, time, lowerMargin, wrapperSize, options) {
let distance = current - start
let speed = Math.abs(distance) / time let {deceleration, itemHeight, swipeBounceTime, wheel, swipeTime} = options
let duration = swipeTime
let rate = wheel ? 4 : 15 let destination = current + speed / deceleration * (distance < 0 ? -1 : 1) if (wheel && itemHeight) {
destination = Math.round(destination / itemHeight) * itemHeight
} if (destination < lowerMargin) {
destination = wrapperSize ? lowerMargin - (wrapperSize / rate * speed) : lowerMargin
duration = swipeBounceTime
} else if (destination > 0) {
destination = wrapperSize ? wrapperSize / rate * speed : 0
duration = swipeBounceTime
} return {
destination: Math.round(destination),
duration
}
}
在该函数中计算步骤如此,首先常规计算出 destination = current + speed / deceleration * (distance < 0 ? -1 : 1)。接着判断按照该结果内容是否超越滚动边界,destination < lowerMargin 时超越滚动下边界,destination > 0 超出滚动上边界。然后再分别使用新的公式计算,注意的是该两个公式使用整个滚动内容的大小,即滚动的范围为公式中的元素,以此保证无法超越滚动边界过多距离。
最后当动量移动结束时,在 _transitionEnd 方法中重新置位即可,关键代码如下。
BScroll.prototype._transitionEnd = function (e) {
if (e.target !== this.scroller || !this.isInTransition) {
return
} this._transitionTime()
if (!this.pulling && !this.resetPosition(this.options.bounceTime, ease.bounce)) {
this.isInTransition = false
if (this.options.probeType !== 3) {
this.trigger('scrollEnd', {
x: this.x,
y: this.y
})
}
}
}
BScroll.prototype.resetPosition = function (time = 0, easeing = ease.bounce) {
let x = this.x
let roundX = Math.round(x)
if (!this.hasHorizontalScroll || roundX > 0) {
x = 0
} else if (roundX < this.maxScrollX) {
x = this.maxScrollX
} let y = this.y
let roundY = Math.round(y)
if (!this.hasVerticalScroll || roundY > 0) {
y = 0
} else if (roundY < this.maxScrollY) {
y = this.maxScrollY
} if (x === this.x && y === this.y) {
return false
} this.scrollTo(x, y, time, easeing) return true
}
better-scroll 源码分析的更多相关文章
- [Android实例] Scroll原理-附ScrollView源码分析
想象一下你拿着放大镜贴很近的看一副巨大的清明上河图, 那放大镜里可以看到的内容是很有限的, 而随着放大镜的上下左右移动,就可以看到不同的内容了 android中手机屏幕就相当于这个放大镜, 而看到的内 ...
- [Android实例] Scroll原理-附ScrollView源码分析 (转载)
想象一下你拿着放大镜贴很近的看一副巨大的清明上河图, 那放大镜里可以看到的内容是很有限的, 而随着放大镜的上下左右移动,就可以看到不同的内容了 android中手机屏幕就相当于这个放大镜, 而看到的内 ...
- jQuery 2.0.3 源码分析 事件体系结构
那么jQuery事件处理机制能帮我们处理那些问题? 毋容置疑首先要解决浏览器事件兼容问题 可以在一个事件类型上添加多个事件处理函数,可以一次添加多个事件类型的事件处理函数 提供了常用事件的便捷方法 支 ...
- BOOtstrap源码分析之 tooltip、popover
一.tooltip(提示框) 源码文件: Tooltip.jsTooltip.scss 实现原理: 1.获取当前要显示tooltip的元素的定位信息(top.left.bottom.right.wid ...
- bootstrap源码分析之scrollspy(滚动侦听)
源码文件: Scrollspy.js 实现功能 1.当滚动区域内设置的hashkey距离顶点到有效位置时,就关联设置其导航上的指定项2.导航必须是 .nav > li > a 结构,并且a ...
- jQuery.lazyload使用及源码分析
前言: 貌似以前自己也写过图片懒加载插件,但是新公司使用的是jQuery.lazyload插件,为了更好的运用,自己还是把源码看了遍,分别记录了如何使用, 插件原理,各个配置属性的完整解释,demo实 ...
- gomoblie flappy 源码分析:游戏逻辑
本文主要讨论游戏规则逻辑,具体绘制技术请参看相关文章: gomoblie flappy 源码分析:图片素材和大小的处理 http://www.cnblogs.com/ghj1976/p/5222289 ...
- Robotium源码分析之运行原理
从上一章<Robotium源码分析之Instrumentation进阶>中我们了解到了Robotium所基于的Instrumentation的一些进阶基础,比如它注入事件的原理等,但Rob ...
- 手机自动化测试:appium源码分析之bootstrap十二
手机自动化测试:appium源码分析之bootstrap十二 poptest是国内唯一一家培养测试开发工程师的培训机构,以学员能胜任自动化测试,性能测试,测试工具开发等工作为目标.如果对课程感兴趣 ...
- 一个普通的 Zepto 源码分析(三) - event 模块
一个普通的 Zepto 源码分析(三) - event 模块 普通的路人,普通地瞧.分析时使用的是目前最新 1.2.0 版本. Zepto 可以由许多模块组成,默认包含的模块有 zepto 核心模块, ...
随机推荐
- 本地如何使用phpstudy环境搭建多站点
http://jingyan.baidu.com/article/e52e36154227ef40c70c5147.html 平时在开发项目的时候, 多个项目同时开发的时候会遇到都得放到根目录才能正常 ...
- 常用排序算法java实现
写在前面:纸上得来终觉浅.基本排序算法的思想,可能很多人都说的头头是到,但能说和能写出来,真的还是有很大区别的. 今天整理了一下各种常用排序算法,当然还不全,后面会继续补充.代码中可能有累赘或错误的地 ...
- [机器学习]-[数据预处理]-中心化 缩放 KNN(二)
上次我们使用精度评估得到的成绩是 61%,成绩并不理想,再使 recall 和 f1 看下成绩如何? 首先我们先了解一下 召回率和 f1. 真实结果 预测结果 预测结果 正例 反例 正例 TP 真 ...
- Java Servlet API中文说明文档
Java Servlet API中文说明文档 目 录 1.... Servet资料 1.1 绪言 1.2 谁需要读这份文档 1.3 Java Servlet API的组成 ...
- jenkins插件之如何优雅的生成版本号
一.简介 在持续集成中,版本管理是非常重要的一部分,本章将介绍如何Version Number Plug插件生成优雅的版本号. 二.安装 系统管理-->插件管理 搜索 Version Numbe ...
- 理解rem实现响应式布局原理及js动态计算rem
前言 移动端布局中,童鞋们会使用到rem作为css单位进行不同手机屏幕大小上的适配.那么来讲讲rem在其中起的作用和如何动态设置rem的值. 1.什么是rem rem是相对于根元素(html标签)的字 ...
- Css3:transform变形
transform 语法: transform 向元素应用 2D 或 3D 转换. transform : none | <<span class="title&quo ...
- 二级缓存:EHCache的使用
EHCache的使用 在开发高并发量,高性能的网站应用系统时,缓存Cache起到了非常重要的作用.本文主要介绍EHCache的使用,以及使用EHCache的实践经验. 笔者使用过多种基于Java的开源 ...
- 编译和解释性语言和python运行方式
1.编译型语言和解释性语言 编译型语言:在执行之前需要一个专门的编译过程,把程序编译成为机器语言的文件,运行时不需要重新翻译,直接使用编译的结果就行了.程序执行效率高,依赖编译器,跨平台性差些.如C. ...
- AppScan扫描结果分析及工具栏使用
Appscan的窗口大概分三个模块,Application Links(应用链接), Security Issues(安全问题), and Analysis(分析) Application Links ...