在外面点击时隐藏DIV [英] Hide DIV when clicked outside
问题描述
我有一个动态生成的表单系统。
I have a form system which is dynamically generated.
以下代码是调用日历的按钮。
<input id="btn1_0" type="button" value="☵" class="rsform-calendar-box btnCal rsform-calendar-button btn btn-default" onclick="RSFormPro.YUICalendar.showHideCalendar('cal1_0Container');">
这是单击上面按钮时显示的div。当在div中单击时,该按钮切换样式 display:none
:
Here's the div which shows up when the above button is clicked. The button toggles the style display:none
when clicked inside the div:
<div id="cal1_0Container" style="clear: both; position: absolute; z-index: 9987;" class="yui-calcontainer single">
Calendar Here
</div>
我想在有人点击div之外时隐藏日历。
I want to hide the calendar when someone clicks outside of the div too.
我试过这个JS,但它不能正常工作,因为它将 display:none
设置为div 。我做错了什么?
I tried this JS but it won't work as it sets display:none
to the div. What am I doing wrong?
jQuery(document).click(function(event) {
if ( !jQuery(event.target).hasClass('yui-calcontainer')) {
jQuery(".yui-calcontainer").hide();
}
});
推荐答案
你可以使用这样的技巧,
检查以下代码
You can use some trick like this , check this code below
$(document).dblclick(function (e)
{
var container = $(".yui-calcontainer");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.hide(); /// or container.toggle(); to show/hide
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<body style="height:100% ; width:100%;";>
<div id="cal1_0Container" style="clear: both; position: absolute; z-index: 9987;" class="yui-calcontainer single">
Calendar Here
</div>
</body>
使用容器.toggle();
for show / hide
use container.toggle();
for show/hide
请告诉我这是否对您有所帮助。
let me know if it this is helpful to you .
这是我的HTMl
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script>
$(document).dblclick(function (e)
{
var container = $(".yui-calcontainer");
if (!container.is(e.target) // if the target of the click isn't the container...
&& container.has(e.target).length === 0) // ... nor a descendant of the container
{
container.toggle();
}
});
</script>
</head>
<body style="height:100% ; width:100%;";>
<div id="cal1_0Container" style="clear: both; position: absolute; z-index: 9987;" class="yui-calcontainer single">
Calendar Here
</div>
</body>
</html>
这篇关于在外面点击时隐藏DIV的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!