/ ** 垂直方向是否在可视区域内 */
function isInViewY(element, offset) {
const pageYScroll = window.pageYOffset || document.documentElement.scrollTop;
const pageHeight = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
const eleRect = element.getBoundingClientRect();
const wt = pageYScroll;
const wb = wt + pageHeight;
const et = wt + eleRect.top;
const eb = et + eleRect.height;
return eb >= wt - offset && et <= wb + offset;
}
/** * 横向方向是否在可视区域内 */
function isInViewX(element, offset) {
const pageXScroll = window.pageYOffset || document.documentElement.scrollLeft;
const pageWidth = window.innerWidth || document.documentElement.clientWidth;
const eleRect = element.getBoundingClientRect();
const wt = pageXScroll;
const wb = wt + pageWidth;
const et = wt + eleRect.left;
const eb = et + eleRect.width;
return eb >= wt - offset && et <= wb + offset;
}
/** * 元素是否在视口中显示 */
function isInView(element, scrollType) {
// 元素露出 2/3 后发送可见曝光统计
const offset = 0;
if (!isInViewY(element, offset)) return false;
// 除了 x 表示横轴滚动,其他均为y轴滚动
if (scrollType !== 'x' || isInViewX(element, offset)) {
return true;
}
return false;
}