正文
- 使用元素位置判斷元素是否在當(dāng)前視區(qū)
這種方法實(shí)現(xiàn)起來比較簡單庭瑰, 我們一步一步來。
首先:編寫一個 util 函數(shù) isVisible沐绒,它將僅接收一個參數(shù)犁柜,即 element剖毯。
export const isVisible = (el) => { };
使用 getBoundingClientRect 獲取該元素的位置
const rect = el.getBoundingClientRect();
將找到窗口的高度和寬度
const vWidth = window.innerWidth || document.documentElement.clientWidth;
const vHeight = window.innerHeight || document.documentElement.clientHeight;
再編寫一個函數(shù)圾笨,該函數(shù)基本上將接收 x 和 y 點(diǎn),并使用elementFromPoint函數(shù)返回元素速兔。
const elementFromPoint = function (x, y) {
return document.elementFromPoint(x, y);
};
檢查元素是否在窗口內(nèi):
// Return false if it's not in the viewport
if (rect.right < 0
|| rect.bottom < 0
|| rect.left > vWidth
|| rect.top > vHeight) {
return false;
}
邊界檢查:
// Return true if any of its four corners are visible
return (
el.contains(elementFromPoint(rect.left, rect.top))
|| el.contains(efp(rect.right, rect.top))
|| el.contains(efp(rect.right, rect.bottom))
|| el.contains(efp(rect.left, rect.bottom))
);
完整代碼:
export const isVisible = (el) => {
const rect = el.getBoundingClientRect();
const vWidth = window.innerWidth || document.documentElement.clientWidth;
const vHeight = window.innerHeight || document.documentElement.clientHeight;
const efp = function (x, y) { return document.elementFromPoint(x, y); };
// Return false if it's not in the viewport
if (rect.right < 0 || rect.bottom < 0
|| rect.left > vWidth || rect.top > vHeight) { return false; }
// Return true if any of its four corners are visible
return (
el.contains(
elementFromPoint(rect.left, rect.top))
|| el.contains(efp(rect.right, rect.top))
|| el.contains(efp(rect.right, rect.bottom))
|| el.contains(efp(rect.left, rect.bottom))
);
};
用法:
import { isVisible } from '../utils';
// ...
const ele = document.getElementById(id);
return isVisible(ele);
邏輯并不復(fù)雜墅拭,不過多介紹。