提交 edc7b710 编写于 作者: Q qiang

feat: 增加 uni.createIntersectionObserver 接口

上级 5b762be8
import Vue from 'vue'
import 'intersection-observer'
const defaultOptions = {
thresholds: [0],
initialRatio: 0,
observeAll: false
}
class MPIntersectionObserver {
_intersectionObserver
_el
_options
_root = null
_rootMargin = '0'
constructor (context, options) {
this._el = context.$el
this._options = Object.assign({}, defaultOptions, options)
}
_makeRootMargin (margins = {}) {
this._rootMargin = ['top', 'right', 'bottom', 'left'].map(name => `${Number(margins[name]) || 0}px`).join(' ')
}
relativeTo (selector, margins) {
this._root = this._el.querySelector(selector)
this._makeRootMargin(margins)
}
relativeToViewport (margins) {
this._root = null
this._makeRootMargin(margins)
}
observe (selector, callback) {
if (typeof callback !== 'function') {
return
}
let options = {
root: this._root,
rootMargin: this._rootMargin,
threshold: this._options.thresholds
}
let intersectionObserver = this._intersectionObserver = new IntersectionObserver((entries, observer) => {
entries.forEach(entrie => {
callback({
intersectionRatio: entrie.intersectionRatio,
intersectionRect: entrie.intersectionRect,
boundingClientRect: entrie.boundingClientRect,
relativeRect: entrie.rootBounds,
time: entrie.time,
dataset: entrie.target.dataset,
id: entrie.target.id
})
})
}, options)
if (this._options.observeAll) {
intersectionObserver.USE_MUTATION_OBSERVER = true
Array.prototype.map.call(this._el.querySelectorAll(selector), el => {
intersectionObserver.observe(el)
})
} else {
intersectionObserver.USE_MUTATION_OBSERVER = false
intersectionObserver.observe(this._el.querySelector(selector))
}
}
disconnect () {
this._intersectionObserver && this._intersectionObserver.disconnect()
}
}
export function createIntersectionObserver (context, options) {
if (!(context instanceof Vue)) {
options = context
context = null
}
if (context) {
return new MPIntersectionObserver(context, options)
}
const pages = getCurrentPages()
if (pages.length) {
context = pages[pages.length - 1]
return new MPIntersectionObserver(context, options)
} else {
UniServiceJSBridge.emit('onError', 'createIntersectionObserver:fail')
}
}
......@@ -49,7 +49,6 @@ export default [
'setBackgroundTextStyle',
'createAnimation',
'loadFontFace',
'createIntersectionObserver',
'getProvider',
'login',
'checkSession',
......
......@@ -3977,6 +3977,10 @@ interpret@^1.0.1:
version "1.2.0"
resolved "https://registry.yarnpkg.com/interpret/-/interpret-1.2.0.tgz#d5061a6224be58e8083985f5014d844359576296"
intersection-observer@^0.7.0:
version "0.7.0"
resolved "https://registry.yarnpkg.com/intersection-observer/-/intersection-observer-0.7.0.tgz#ee16bee978db53516ead2f0a8154b09b400bbdc9"
invariant@^2.2.2:
version "2.2.4"
resolved "https://registry.yarnpkg.com/invariant/-/invariant-2.2.4.tgz#610f3c92c9359ce1db616e538008d23ff35158e6"
......
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册