1

我试图在一个自定义框中显示错误,其中包含一些信息(行号,文件名......),在一个覆盖页面正文并避免与框外元素交互的 DIV 内。

这是 DIV 的 CSS:

overlayStyle = {
    'position': 'absolute',
    'top': '0px',
    'left': '0px',
    'height': '100%',
    'width': '100%',
    'backgroundColor': 'rgba(199,199,199,0.7)',
    'display': 'block',
    'zIndex': '1000',
    'textAlign': 'center',
    'paddingTop': '5%'
}

我正在通过对文档的 HEAD 部分中不存在的文件进行 AJAX 调用来测试这一点,因此该框在文档加载时打开。这是 onerror 处理程序:

window.onerror = function ( msg, url, line ) {
    error ( msg, url, line );
    return true;
}

这是创建盒子的脚本的一部分:

var root = document.documentElement.scrollTop ? document.documentElement : document.body;
root.scrollTop = 0;

document.body.style.overflow = 'hidden';

在这里,我将文档滚动到顶部,以便仅显示具有 0,0 坐标的覆盖 DIV。

如果我关闭错误框,向下滚动页面并发送 F5,页面重新加载滚动到底部,但覆盖的 DIV 位于 0,0,所以我只看到它的底部。

那是因为 scrollTop 位置(我也试过 window.scrollY)是 0 所以 root.scrollTop = 0; 不会产生任何效果。

有什么方法可以正确定位 DIV(请不要使用 jQuery)?

这是完整的代码:

function error ( msg, url, line ) {
    var overlay = document.createElement ( 'DIV' ),
    scrollPos = 0,
    root = document.documentElement.scrollTop ? document.documentElement : document.body,
    overlayId = 'divErrorOverlay',
    overlayStyle = {
            'position': 'absolute',
            'top': '0px',
            'left': '0px',
            'height': '100%',
            'width': '100%',
            'backgroundColor': 'rgba(199,199,199,0.7)',
            'display': 'block',
            'zIndex': '1000',
            'textAlign': 'center',
            'paddingTop': '5%'
    },
    errHead = null,
    errBody = null;

    overlay.setAttribute ( 'id', overlayId );
    for ( var i in overlayStyle ) overlay.style [ i ] = overlayStyle [ i ];

    scrollPos = root.scrollTop; //I use this to restore position when box is closed
    root.scrollTop = 0;

    document.body.appendChild ( overlay );
    document.body.style.overflow = 'hidden';

    //Calls to methods that creates header and body
}
4

0 回答 0