实现元素曝光的方法
1.js实现元素曝光 2.使用js的库实现元素曝光
1. js实现元素曝光的难点
1.如何判断一个元素是否曝光 2.如何监听
如何判断一个元素是否曝光
private isElementInViewport(el): boolean {
let rect = el.getBoundingClientRect();
return (
rect.top >= 0 &&
rect.left >= 0 &&
rect.bottom <=
(window.innerHeight || document.documentElement.clientHeight) &&
rect.right <=
(window.innerWidth || document.documentElement.clientWidth)
);
}
如何监听
let questionClassElements = document.getElementsByClassName('problemClass-content')[0];
let commonProblemElements = document.getElementsByClassName('commonProblem-content')[0];
this.problemMode = [
{ element: questionClassElements, reportCustomId: 'questionClass', isReported: false },
{ element: commonProblemElements, reportCustomId: 'commonQuestion', isReported: false }
];
//上报事件
reportCustomMode(): void {
let that = this;
this.problemMode.map((problem) => {
if(problem.isReported === true) {
return false;
}
if(problem.isReported === false && that.isElementInViewport(problem.element)) {
problem.isReported = true;
reportCustom(`pv-${problem.reportCustomId}`); //上报的方法
}
});
}
//滚动事件
private onScroll() {
this.reportCustomMode();
}
//监听滚动事件
document.addEventListener('scroll', this.onScroll);
2.使用js的库实现元素曝光
推荐使用vue-exposure库 使用, 1.下载vue-exposure 2.在main.js引入,并且使用
import Exposure from 'vue-exposure/dist/exposure-polyfill'
Vue.use(Exposure)
3.在相关的dom元素上使用
<div v-exposure="exposeGame(game)" >
111
</div>
exposeGame(game) {
//曝光事件
},
```
|