当foucs出局或在div外部点击时隐藏div

时间:2017-02-15 12:05:39

标签: javascript jquery html css

在像这样的html结构中

date

输入框是自动填充的,每个国家/地区都附加到<div class="col-sm-4 blockDiv" id="focusDiv"> <div style="height:51px;padding:1em;background-color:white;" id="totalSel">Countries visited in last 6days?</div> <div style="background-color:white;" id="bg-div"> <ul id="testMulti"> <li> <span class="textinput" style="display:block;"> <input type="text" id="countriesVisited"> <label for="countriesVisited">Countries visited in last 6days?</label> <input type="hidden" id="countriesVisited-val" name="countriesVisited-val" value=""> </span> </li> <li class="selected2 mulSel"><span class="mulSel1">Indonesia</span><span class="remove">x</span> </li> </ul> <div style="clear:both;"></div> </div> </div> 标记。当用户在此div之外点击时,我想隐藏ID为ul的div

3 个答案:

答案 0 :(得分:2)

假设outside的{​​{1}}无处不在,除了上面提到的元素本身,您可以这样尝试:

<body>
$(document).on('click', 'body', function(event){
    if('focusDiv' === $(event.target).attr('id')) {
      return;
    }
  
    $('#focusDiv').hide();
});
#focusDiv {
  width:200px;
  height: 200px;
  border: solid 2px orange;
  padding: 20px;
}

答案 1 :(得分:0)

好的,你应该在外面点击时尝试隐藏div

$(document).mouseup(function (e)
{
    var container = $("#focusDiv");

    if (!container.is(e.target) && container.has(e.target).length === 0)
    {
        container.hide();
    }
});

答案 2 :(得分:0)

或者您可以查看$(e.target).parents('#focusDiv').length

&#13;
&#13;
$(document).on('click', function(e) {
  if (!$(e.target).parents('#focusDiv').length) {
    $('#focusDiv').hide();
  }
});
&#13;
#focusDiv {
  border: 1px solid #000
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="col-sm-4 blockDiv" id="focusDiv">
  <div style="height:51px;padding:1em;background-color:white;" id="totalSel">Countries visited in last 6days?</div>
  <div style="background-color:white;" id="bg-div">
    <ul id="testMulti">
      <li>
        <span class="textinput" style="display:block;">
    <input type="text" id="countriesVisited">
    <label for="countriesVisited">Countries visited in last 6days?</label>
    <input type="hidden" id="countriesVisited-val" name="countriesVisited-val" value="">
    </span>
      </li>
      <li class="selected2 mulSel"><span class="mulSel1">Indonesia</span><span class="remove">x</span>
      </li>
    </ul>
  </div>
</div>
&#13;
&#13;
&#13;