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
                });
            })
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值