js点击input弹出一个框div,点击输入框和div之外的地方隐藏弹出框

利用了阻止冒泡的方法实现,先上样式

    <input type="text" name="" id="" placeholder="请输入">
    <div class="box">
        <div class="box1">
            戳我
        </div>
    </div>
    <style>
        .box {
    
    
            width: 200px;
            height: 200px;
            border: 1px solid red;
            display: flex;
            justify-content: center;
            align-items: center;
            display: none;
        }
        .box1 {
    
    
            width: 100px;
            height: 100px;
            border: 1px solid green;
        }
    </style>

1、js代码:原生js

        window.onload=function(){
    
    
            var input=document.getElementsByTagName("input")[0]
            var box=document.getElementsByClassName("box")[0]
            input.onclick=function(event){
    
    
                box.style.display="block"
                event.stopPropagation()//这里是关键,阻止冒泡
            }
            document.onclick=function(){
    
    
                box.style.display="none"//点击文档document隐藏box
            }
            box.onclick=function(event){
    
    
                event.stopPropagation()//点击box本身,阻止冒泡
            }
        }

2、js代码:jquery

        $(function () {
    
    
                $("input").click(function(){
    
    
                    $(".box").show();
                    return false;//关键是这里,阻止冒泡
                });
                $(".box").click(function(){
    
    
                    return false;//点击box本身,阻止冒泡
                });
                $(document).click(function(){
    
    
                    $(".box").hide();//点击文档document隐藏box
                });
            })

猜你喜欢

转载自blog.csdn.net/LiuPangZi6/article/details/103001477