在单击 div 区域外部时关闭 div。

5

我有这段代码。当在Div外面单击时,我想要关闭它。我已经在论坛上搜索过,但找不到解决方案- 这里是一个fiddle- 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()

“outside the div” 是什么意思?这个 div 会被包裹在另一个 div 中吗?还是其他 HTML 容器中? - Thanu
我是指除了req div内部以外的页面上任何地方都可以点击。 - kunz
4个回答

5
请求的Div宽度为屏幕宽度的100%。frame的宽度与边框相同。

$('#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>


1
@jake123 你看看我的解决方案。它能够与你的代码互不干扰,并且避免事件冲突。 - Reagan Gallant
非常感谢,它完美地运行了,正是我所需要的。只需进行一些编辑,它就可以工作了:D :D :D 谢谢您。 - kunz

2
请看这个。
$('html').click(function() {
  $("#req").hide();
  // add some code
});

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

在这里测试代码JSFiddle


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

然而,对于你想做的事情,你只需要传递一个选择器给.is(),像这样:

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

这里有一个可用的 jsFiddle 示例。 (请注意,如果您点击 div 右侧,它将无法工作,但这是因为您仍然在点击 #req,因为它没有指定宽度。)

小提琴运行良好,但当我在网页中实现相同的东西时,它不起作用。 - kunz
是因为我在同一页中有另一个切换选项吗? - kunz
1
抱歉,我无法确定。如果在fiddle中可以运行但在您的代码中无法运行,则可能存在许多问题,包括其他事件冲突或停止了本应该执行的操作。 - Ken Herbert
有没有其他的方法来做这件事? - kunz
在 JavaScript 中,几乎总有多种方法来完成某件事情。我刚刚给你提供了一种方法。 - Ken Herbert
你能否提供另一种解决方案? - kunz

0

你需要在文档中添加点击事件,并检查被点击的目标及其任何父级是否都没有必需的类:

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


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接