首页 > 解决方案 > 创建带有空白背景屏幕的警报弹出窗口

问题描述

我需要显示一个警告框,同时覆盖我的 HTML 页面上的内容。基本上,当我的警报弹出窗口出现时,我希望有一个空白或白色背景。我尝试了类似下面的方法,但不起作用。

if (something happens) {

    changeBackgroundColor();

    if (alert("My alert box")){

    } else {
        //Return to previous page
        window.history.go(-1);
    }
}

..
....
.....

function changeBackgroundColor() {
    document.body.style.backgroundColor = "white";
} 

标签: javascriptcss

解决方案


更改背景颜色不会隐藏页面上的任何元素。您很可能需要一个叠加层,它可以是一个简单的 div 样式,如下所示:

.overlay {
    position:fixed;
    top:0;
    left:0;
    right:0;
    bottom:0;
    z-index:999; /* adjust the z-index as you need it */
    background:#fff;
    display:none;
}

然后,您可以在警报之前显示叠加层并在之后隐藏它

function toggleOverlay( show ){
    document.querySelector('.overlay').style.display = (show === true) ? 'block' : 'none';
}

// ...

toggleOverlay(true);
// Kudos to Kobe for pointing out that the alert is triggered before the repaint
// simple way to solve the problem is a timeout, which will
// make the browser paint the changes before the alert is triggered
setTimeout(function(){
    alert('Something');
    toggleOverlay(false);
}, 0);

这是一个有效的 jsFiddle:https ://jsfiddle.net/UsernamesSuck/cpdrtgb8/2/


推荐阅读