定位灯箱的问题

时间:2013-05-30 17:57:49

标签: javascript html css

我正在尝试创建一个灯箱,该灯箱最好应该基于最少量的JS(框架,但它们可能是“光”,允许)。在各种资源的帮助下,我写了以下一点JS:

var dialogWritten = false;

function getZIndex(elem) {
    var elems = document.getElementsByTagName(elem);
    var highest = 0;
    for (var i = 0; i < elems.length; i++) {
        var zindex = document.defaultView.getComputedStyle(elems[i], null).getPropertyValue("z-index");
        if ((zindex > highest) && (zindex != 'auto')) {
            highest = zindex;
        }
    }
    return highest;
}

function displayDialog() {
    if (!dialogWritten) {
        var backgroundOverlay = document.createElement("div");
        backgroundOverlay.style.display = "block";
        backgroundOverlay.style.position = "absolute";
        backgroundOverlay.style.top = "0%";
        backgroundOverlay.style.left = "0%";
        backgroundOverlay.style.width = "100%";
        backgroundOverlay.style.height = "100%";
        backgroundOverlay.style.backgroundColor = "#000000";
        backgroundOverlay.style.zIndex = getZIndex('*') + 1;
        backgroundOverlay.style.opacity = "0.8";
        document.body.appendChild(backgroundOverlay);
        dialogWritten = true;

        var configDialog = document.createElement("div");
        configDialog.style.display = "block";
        configDialog.style.position = "absolute";
        configDialog.style.top = "25%";
        configDialog.style.left = "25%";
        configDialog.style.width = "50%";
        configDialog.style.height = "50%";
        configDialog.style.backgroundColor = "#acacac";
        configDialog.style.zIndex = getZIndex('*') + 1;
        configDialog.style.padding = "10px";
        configDialog.style.fontFace = "sans-serif";
        configDialog.innerHTML = '<p>Configuration dialog</p>';
        document.body.appendChild(configDialog);
        dialogWritten = true;
    }
}

灯箱显然有效,但事实证明叠加层仅适用于页面的最顶部,而不适用于下部。

屏幕截图有助于说明清楚:

screenshot: Lightbox applies to the above part screenshot: Lightbox does not apply to lower sections

为了使灯箱的叠加层适用于整个页面,我该怎么办?

提前感谢您的帮助。

2 个答案:

答案 0 :(得分:1)

这取决于您想要达到的目标 - 您是否希望修复灯箱位置(相对于视口)?如果是这种情况,那很简单 - 只需将位置设置为固定而不是绝对。

OP澄清后编辑:

如果您希望灯箱叠加层应用于整个页面,请将背景叠加层的位置设置为固定。

答案 1 :(得分:0)

更改

backgroundOverlay.style.position = "absolute";

backgroundOverlay.style.position = "fixed";

configDialog.style.position = "absolute";

configDialog.style.position = "fixed";