js实现点击空白处隐藏

技术栈涉及阻止冒泡的方法和怎样判断点击的是当前对象,都是一些工作中比较常用的知识点。

<!DOCTYPE html>
<html>
<head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style>
        body {
            height:2000px;
        }
        #mask {
            width: 100%;
            height: 100%;
            opacity: 0.4;   /*半透明*/
            filter: alpha(opacity = 40);  /*ie 6半透明*/
            background-color: black;
            position: fixed;
            top: 0;
            left: 0;
            display: none;
        }
        #show {
            width: 300px;
            height: 300px;
            background-color: #fff;
            position: fixed;
            left: 50%;
            top: 50%;
            margin: -150px 0 0 -150px;
            display: none;
        }
    </style>
</head>
<body>
<a href="javascript:;" id="login">注册</a>
<a href="javascript:;">登录</a>
<div id="mask"></div>
<div id="show"></div>
</body>
</html>
<script>
    function $(id) { return document.getElementById(id);}
    var login = document.getElementById("login");
    login.onclick = function(event) {
        $("mask").style.display = "block";
        $("show").style.display = "block";
        document.body.style.overflow = "hidden";  // 不显示滚动条
        //取消冒泡
        var event = event || window.event;
        if(event && event.stopPropagation)
        {
            event.stopPropagation();
        }
        else
        {
            event.cancelBubble = true;
        }
    }
    document.onclick = function(event) {

        var event = event || window.event;
        // alert(event.target.id);  // 返回的是点击的某个对象的id 名字
        // alert(event.srcElement.id);
        var targetId = event.target ? event.target.id : event.srcElement.id;
        // 看明白这个写法
        if(targetId != "show")  // 不等于当前点点击的名字
        {
            $("mask").style.display = "none";
            $("show").style.display = "none";
            document.body.style.overflow = "visible"; // 显示滚动条
        }
    }
</script>

猜你喜欢

转载自blog.csdn.net/qq_36818627/article/details/81610892
今日推荐