/** * 垂直方向是否在可視區域內 */ function isInViewY(element, offset) { const pageYScroll = window.pageYOffset || document.documentElement.scrollTop; const pageHe ...
/** * 垂直方向是否在可視區域內 */
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;
}