使用 JavaScript 检测页面中心点和交叉线上的 DOM 元素

26 阅读1分钟
document.addEventListener('DOMContentLoaded', function() {
function isElementVisible(element) {
    const rect = element.getBoundingClientRect();
    const windowHeight = window.innerHeight || document.documentElement.clientHeight;
    const windowWidth = window.innerWidth || document.documentElement.clientWidth;

    // 检查元素是否在视口内
    const isVisible = (
        rect.top >= 0 &&
        rect.left >= 0 &&
        rect.bottom <= windowHeight &&
        rect.right <= windowWidth
    );

    return isVisible;
}

function checkCenterAndCrossLines() {
    const windowHeight = window.innerHeight || document.documentElement.clientHeight;
    const windowWidth = window.innerWidth || document.documentElement.clientWidth;

    // 页面中心点
    const centerX = windowWidth / 2;
    const centerY = windowHeight / 2;

    // 检查页面中心点的元素
    const centerElement = document.elementFromPoint(centerX, centerY);
    if (centerElement && isElementVisible(centerElement)) {
        console.log('页面中心点有可见元素:', centerElement);
        return false;
    }

    // 检查垂直线上的元素
    for (let y = 0; y < windowHeight; y += 10) {
        const element = document.elementFromPoint(centerX, y);
        if (element && isElementVisible(element)) {
            console.log('垂直线上有可见元素:', element);
            return false;
        }
    }

    // 检查水平线上的元素
    for (let x = 0; x < windowWidth; x += 10) {
        const element = document.elementFromPoint(x, centerY);
        if (element && isElementVisible(element)) {
            console.log('水平线上有可见元素:', element);
            return false;
        }
    }

    // 如果没有检测到可见元素,则可能是白屏
    console.error('可能出现白屏问题');
    return true;
}

const isBlankScreen = checkCenterAndCrossLines();
if (isBlankScreen) {
    // 处理白屏问题,例如:重新加载页面或记录错误日志
}
});