美文网首页
除指定区域外点击任何地方隐藏DIV

除指定区域外点击任何地方隐藏DIV

作者: 一名有马甲线的程序媛 | 来源:发表于2017-11-28 18:08 被阅读2820次

html如下:

    <div class="btn" id="btn">btn</div>
    <div class="box"></div>

jquery(法一)如下:

$('.btn').on('click',function(e){
    $('.box').show();
    e.stopPropagation();
})
$('body').on('click',function(){
    $('.box').hide();
})

jquery(法二)如下:

    $('body').click(function(e) {
        var target = $(e.target);

        // 如果#overlay或者#btn下面还有子元素,可使用
        // !target.is('#btn *')
        if(target.is('#btn')){
            $('.box').show();
        }else{
            $('.box').hide();
        }
    });

jquery(法三)如下:

    //判断:当前元素是否是被筛选元素的子元素 
    // jQuery.fn.isChildOf = function(b){ return (this.parents(b).length > 0); }; 

    //判断:当前元素是否是被筛选元素的子元素或者本身 
    jQuery.fn.isChildAndSelfOf = function(b){ return (this.closest(b).length > 0); };
    $(document).click(function(event){ 
        if(!$(event.target).isChildAndSelfOf('#btn')){
            $('.box').hide();
        }
    });

    $('#btn').on('click',function(){
        $('.box').show();
    })

css如下:(随便写)

        .box{
            width:500px;
            height:100px;
            background: pink;
        }
        .btn{
            width:100px;
            height:30px;
            text-align: center;
            line-height: 30px;
            cursor: pointer;
            background: #ff8800;
            border-radius: 3px;
            margin-bottom: 10px;
            color:#fff;
        }

补充:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>点击其它地方关闭DIV</title>
</head>
 
<body>
<input type="text" value="" id="tf"/>
<div style="width:400px; height:200px;border:1px solid #000;display:none" id="con">
     <p>1111</p>
     <p><span>2222</span></p>
     <p><a href="#">3333</a></p>
</div>
<script>
  function e(obj){
    return document.getElementById(obj)
  }
  e('tf').onclick=function(event){
    e('con').style.display='block';
    stopBubble(event); 
    document.onclick=function(){
      e('con').style.display='none';
   document.onclick=null; 
    }
  }
   
  e('con').onclick=function(event){
    //只阻止了向上冒泡,而没有阻止向下捕获,所以点击con的内部对象时,仍然可以执行这个函数
    stopBubble(event); 
  }
  //阻止冒泡函数
  function stopBubble(e){  
    if(e && e.stopPropagation){
      e.stopPropagation();  //w3c
    }else{
      window.event.cancelBubble=true; //IE
    }
  }
</script>
</body>
</html>

demo网址:https://pan.baidu.com/s/1c167Y84

相关文章

网友评论

      本文标题:除指定区域外点击任何地方隐藏DIV

      本文链接:https://www.haomeiwen.com/subject/koyebxtx.html