[英]close div when clicked outside the div area
我有这段代码。我正在尝试关闭div,当在Div之外点击时,我已经搜索了这个论坛但找不到解决方案 - 这里是一个小提琴 - 演示
$('#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()
Div req
width是屏幕的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>
请检查一下。
$('html').click(function() {
$("#req").hide();
// add some code
});
$('#clickme').click(function(event) {
event.stopPropagation();
// add some code
});
测试代码在这里jsfiddle
.is()
的函数参数用于测试集合中的每个元素,并且需要返回一个布尔值,以确定元素是否匹配 - 它不应该返回jQuery集合。
但是,对于您要做的事情,您应该只将选择器而不是函数传递给.is()
如下所示:
if (e.keyCode === 27 || !$(e.target).is("#req, #hideshow1")) {
$("#req").hide()
}
这是一个有效的jsFiddle 。 (请注意,如果单击div的右侧,它将无法工作,但这是因为您仍然单击#req
因为它没有指定的宽度。)
您需要将click事件添加到文档并检查单击的目标,并且其中任何父目录都没有必需的类:
$(document).on('click', function (e) { var divClass = 'my-class'; if (!$(e.target).hasClass(divClass) && !$(e.target).parents().hasClass(divClass)) { // do something... } });
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.