在div区域外单击时关闭div

时间:2016-03-08 01:29:54

标签: jquery

我有这段代码。我正在尝试关闭div,当在Div之外点击时,我搜索了这个论坛但找不到解决方案 - 这是一个小提琴 - Demo

$('#hideshow1').on("click", function() {
    var text = $(this).val();
    $("#req").toggle();

});

$(window).on("click keydown", function(e) {
  //e.preventDefault() /*For the Esc Key*/
  if (e.keyCode === 27 || !$(e.target).is(function() {return $("#req, #hideshow1")})) {
    $("#req").hide()
  }
}).focus()

4 个答案:

答案 0 :(得分:5)

Div frame宽度是屏幕的100%。 $('#hideshow1').on("click", function() { if ($("#frame").is(":visible") == false) { $("#frame").show(); } $('#hideshow1').text("Click outside div to hide it."); }); $(document).mouseup(function(e) { var container = $("#frame"); //Used frame id because div(req) width is not the same as the frame if ($("#frame").is(":visible")) { if (!container.is(e.target) //check if the target of the click isn't the container... && container.has(e.target).length === 0) { container.hide(); $('#hideshow1').text("Click to see div"); } } });宽度与边框相同。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<div id="clickme">
  <a class="req_pic_link" id="hideshow1">Click outside div to hide it.</a>
</div>
<div id="req">
  <iframe id="frame" src="https://www.google.com"></iframe>
</div>
TextView

答案 1 :(得分:2)

请检查一下。

$('html').click(function() {
  $("#req").hide();
  // add some code
});

$('#clickme').click(function(event) {
  event.stopPropagation();
  // add some code
});

此处测试代码jsfiddle

答案 2 :(得分:2)

.is()的函数参数用于测试集合中的每个元素,并且需要返回一个布尔值,以确定元素是否匹配 - 它不应该返回jQuery集合。

但是,对于您要做的事情,您应该只将选择器而不是函数传递给.is(),如下所示:

if (e.keyCode === 27 || !$(e.target).is("#req, #hideshow1")) {
    $("#req").hide()
}

这是一个有效的jsFiddle。 (请注意,如果单击div的右侧,它将无效,但这是因为您仍然点击#req,因为它没有指定的宽度。)

答案 3 :(得分:0)

您需要在文档中添加点击事件,并检查点击的目标,并且其中任何一个父级都没有必需的课程:

&#13;
&#13;
$(document).on('click', function (e) {
  var divClass = 'my-class';
  if (!$(e.target).hasClass(divClass) && !$(e.target).parents().hasClass(divClass)) {
    // do something...
  }
});
&#13;
&#13;
&#13;

相关问题