首页 > 其他分享 >js/jq 点击按钮显示div,点击页面其他任何地方隐藏div

js/jq 点击按钮显示div,点击页面其他任何地方隐藏div

时间:2022-10-31 15:56:58浏览次数:61  
标签:function 浮层 jq pop 点击 div stopPropagation

1、HTML页面

<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>无标题文档</title>
    <style type="text/css">
        #pop {
            border: #000;
            background-color: #CCC;
            position: absolute;
            left: 50px;
            top: 50px;
            width: 200px;
            height: 500px;
            display: none;
        }

        #btn {
            color: #f00;
        }
    </style>
</head>
<body>
    <span id="btn">打开层</span>
    <div>aaaaaaaaaaaa</div>
    <div>aaaaaaaaaaaa</div>

    <div id="pop">
        浮层,点击这个浮层以外的区域,都可以隐藏这个浮层
        <p><a href="javascript:;">最主要的是点这个div里面的链接,div照样不隐藏</a></p>
    </div>
</body>
</html>

 2、js 实现

<script type="text/javascript">
    function $(id) { return document.getElementById(id); }
    window.onload = function () {
        document.onclick = function (e) {
            $("pop").style.display = "none";
        }
        $("btn").onclick = function (e) {
            $("pop").style.display = "block";
            e = e || event; stopFunc(e);
        }
        $("pop").onclick = function (e) {
            e = e || event; stopFunc(e);
        }
    }
    function stopFunc(e) {
        e.stopPropagation ? e.stopPropagation() : e.cancelBubble = true;
    }
</script>

3、JQuery 实现

$("#btn").on("click", function(e){
    $("#menu").show();

    $(document).one("click", function(){
        $("#menu").hide();
    });

    e.stopPropagation();
});
$("#menu").on("click", function(e){
    e.stopPropagation();
});

原文链接:https://blog.csdn.net/yangbingx/article/details/78644486

 

标签:function,浮层,jq,pop,点击,div,stopPropagation
From: https://www.cnblogs.com/fairya/p/16844538.html

相关文章