利用冒泡原理实现蒙版效果

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        html,body{
            width: 100%;
            height: 1200px;
        }
        #panel{
            width: 100%;
            height: 100%;
            background: #000;
            opacity: 0.4;
            filter: alpha(opacity:40);
            position: absolute;
            top:0;
            left: 0;
            display: none;
        }
        #login{
            width: 300px;
            height: 300px;
            background: skyblue;
            text-align: center;
            line-height: 300px;
            position: fixed;
            left: 50%;
            top:50%;
            transform: translate(-50%,-50%);
            display: none;
        }
    </style>
</head>
<body>
<button id="btn">立即登录</button>
<div id="panel"></div>
<div id="login">登录面板</div>
<script>
    /*
    * 如果有document(父子)事件要注意冒泡
    * 这里btn事件冒泡到document,使  panel.style.display先block,再none
    * */
window.onload=function () {
    let btn=document.getElementById("btn")
    let panel=document.getElementById("panel")
    let login=document.getElementById("login")
    btn.onclick=function (event) {
        let e=event || window.event
        //阻止冒泡
        if(e.stopPropagation){
           e.stopPropagation()
        }else{
            e.cancelBubble=true
        }
       panel.style.display="block"
       login.style.display="block"
        //隐藏滚动条
        document.documentElement.style.overflow="hidden"

    }
    //点击文档
    document.onclick=function () {
        let e=window.event || arguments[0]
        //获取点击标签的id(兼容)
        let target=e.target?e.target.id:e.srcElement.id
        if(target!="login"){
             panel.style.display="none"
             login.style.display="none"
             document.documentElement.style.overflow="visible"
        }else {
            location.href="https://www.baidu.com/"
        }
    }

}
</script>
</body>
</html>
posted @ 2020-06-17 23:18  岱宗如何  阅读(141)  评论(0编辑  收藏  举报