在外面点击时隐藏DIV
我有一个动态生成的表单系统。
下面的代码是调用日历的按钮。
这是在单击上面的按钮时显示的div。 按钮切换样式display:none
在div中单击时display:none
:
Calendar Here
我想在有人点击div之外时隐藏日历。
我试过这个JS,但它不能正常工作,因为它将display:none
设置为div。 我究竟做错了什么?
jQuery(document).click(function(event) { if ( !jQuery(event.target).hasClass('yui-calcontainer')) { jQuery(".yui-calcontainer").hide(); } });
您无法将单击事件绑定到文档。 把它绑在身上。
jQuery('body').click(function(event) { if ( !jQuery(event.target).hasClass('yui-calcontainer')) { jQuery(".yui-calcontainer").hide(); } }); or jQuery(document).on('click', 'body', function(event) { if ( !jQuery(event.target).hasClass('yui-calcontainer')) { jQuery(".yui-calcontainer").hide(); } });
您可以使用这样的技巧,请查看下面的代码
$(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 } });
Calendar Here
看起来您正在尝试使用YUICalendar库,在这种情况下,查看官方文档可能会有所帮助@ https://developer.yahoo.com/yui/calendar/
我找到了一个可能实现您想要实现的目标的示例: https : //developer.yahoo.com/yui/examples/calendar/calcontainer_clean.html