Intersection Observer
w3c中的一個新興api,兼容性并不好,IE瀏覽器全軍覆沒蜗搔,詳情可can i use。
作用:異步觀察目標(biāo)元素與其祖先元素或頂級文檔視窗(viewport)交叉狀態(tài)的方法缝龄。具體可見文檔
polyfill版本
鑒于兼容性問題服鹅,w3c提供了一個npm包,提供了polyfill版本。下載地址
npm install intersection-observer
使用
廢話不多說,上代碼
- 創(chuàng)建一個文件苇倡,基于intersection observer進(jìn)行封裝
import 'intersection-observer';
IntersectionObserver.prototype.POLL_INTERVAL = 300; // 節(jié)流時間為300毫秒
class Exposure {
// _observerArr = [];
constructor(maxNum) {
this.maxNum = maxNum;
this._observer = null; // 監(jiān)聽對象
this.exposureList = {}; // 存儲監(jiān)聽對象想要操作的數(shù)據(jù)综慎,例如統(tǒng)計數(shù)據(jù)
this.init();
}
init() {
console.log('exposure init!');
const self = this;
this._observer = new IntersectionObserver(function (entries, observer) {
// console.log(entries);
// console.log(observer);
// console.log(self.exposureList);
entries.forEach(entry => {
const id = entry.target.attributes['data-id'].value || ''; // 可以通過id記錄標(biāo)示數(shù)據(jù)愉镰,id需唯一
console.log('id', id);
const exposureData = self.exposureList[id] || {};
// 如果被監(jiān)聽元素顯示在視窗內(nèi),并且有數(shù)據(jù)类嗤,沒有開始時間货裹,則添加開始時間赋兵,用作計算被監(jiān)聽元素在視窗停留的時間
if (entry.isIntersecting && JSON.stringify(exposureData) !== '{}' && !exposureData.start_time) {
self.exposureList[id] = Object.assign(exposureData, {
start_time: Date.now(),
});
}
// 如果監(jiān)聽元素,從視窗消失历造,并且有統(tǒng)計數(shù)據(jù)鸭轮,并且有開始時間
if (!entry.isIntersecting && JSON.stringify(exposureData) !== '{}' && exposureData.start_time) {
const end_time = Date.now();
// 如果被監(jiān)聽元素在視窗停留的時間大于300毫秒邑蒋,則上報數(shù)據(jù)
if (end_time - exposureData.start_time > 300) {
mini.reportSCData('product_exposure', {
...exposureData,
end_time,
});
}
delete exposureData['start_time'];
self.exposureList[id] = exposureData;
}
});
}, {
root: null, // 所監(jiān)聽對象的具體祖先元素,未傳入值或值為`null`,則默認(rèn)使用頂級文檔的視窗。
rootMargin: '0px 0px 0px 0px', // 計算交叉時添加到根(root)邊界盒bounding box的矩形偏移量麦箍, 可以有效的縮小或擴(kuò)大根的判定范圍從而滿足計算需要
threshold: 0, // 一個包含閾值的列表, 按升序排列, 列表中的每個閾值都是監(jiān)聽對象的交叉區(qū)域與邊界區(qū)域的比率。
});
}
add(el, value, vnode) {
if (this._observer) {
// 使IntersectionObserver開始監(jiān)聽一個目標(biāo)元素。
this._observer.observe(el);
this.exposureList[el.dataset.id] = {
...value,
};
}
}
remove() {
// 使IntersectionObserver對象停止監(jiān)聽工作
this._observer.disconnect();
}
}
export default Exposure;
- 創(chuàng)建自定義指令,添加監(jiān)聽元素
import Vue from 'vue';
import Exposure from '@/utils/exposure';
const exp = new Exposure();
Vue.directive('exposure', {
bind(el, binding, vnode) {
exp.add(el, binding.value);
},
})
- 頁面組件份名,使用指令
<div v-dwdExposure="exposureData" :data-id="id"></div>