我需要做一个功能,显示菜单,如果用户点击特定的div。然后我需要隐藏它,如果用户点击网站上的任何地方,除了一个特定的div。
例如
<div class="showMeHideMe" style="display:none;">Example</div>
<div class="showIt">Show it!</div>然后我的JavaScript
jQuery('.showIt').click(function(){
$('.showMeHideMe').show();
});
jQuery(document).not('.showMeHideMe').click(function(){
$('.showMeHideMe').hide();
});如果我点击.showIt,一切都很好,.showMeHideMe也显示出来了。如果我点击页面上的任何位置,.showMeHideMe就会隐藏起来。也没问题。但是,如果它显示,我点击.showMeHideMe,它会隐藏自己。这是错误的。
你能告诉我我做错了什么吗?
更新
非常感谢您的快速答复。
我想在我需要修复的页面上显示它会更好。现在我的代码如下所示:
<div class="search--box">
<div class="search--box-inner">
<form role="search" method="get" id ="searchform" action="">
<input class="search--box--input" name="s">
</input>
</form>
</div>
</div>以及应该处理这件事的JavaScript
jQuery(".search--box").hide();
jQuery(".desktop-search").mouseenter(function (e) {
e.stopPropagation();
jQuery(".search--box").show();
jQuery(".search--box--input").focus();
});
jQuery(document).not('input.search--box--input').click(function (e) {
e.stopPropagation();
jQuery(".search--box").hide();
});此外,带有: not,而不是.not()的变量也不起作用。尽管如此,如果我点击输入,它仍然在隐藏。
发布于 2016-12-19 10:08:56
最后,我们使用条件来处理它,检查单击的元素是否有特定的类。
$(document).not('input.search--box--input').click(function (e) {
e.stopPropagation();
if ($(e.target).hasClass('search--box--input')) {
return;
}
$(".search--box").hide();
});也许它可以适用于和我有同样问题的人:)
发布于 2016-12-17 20:56:21
您可以在单击stopPropagation内使用showIt,而另一个函数将只处理对document的单击。
jQuery('.showIt').click(function(e){
e.stopPropagation();
$('.showMeHideMe').show();
});
jQuery(document).click(function(){
$('.showMeHideMe').hide();
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showMeHideMe" style="display:none;">Example</div>
<div class="showIt">Show it!</div>
这样--当您单击文档时-- .showMeHideMe将被隐藏,,除非单击了.showIt元素,而且在这里,对stopPropagation()的调用将确保其他hide函数不会被调用。
发布于 2016-12-17 21:06:27
而不是这一行:
jQuery(document).not('.showMeHideMe').click(function(){你可以委托:
jQuery(document).on('click', ':not(.showIt)', function(e) {这样,您将匹配dom中的每个当前元素和未来元素,而不是“showIt”元素。
当用户单击“showIt”元素外部时,事件序列(bubling)是:
因此,您可以停止这些事件的传播,并且只使用第一个事件来关闭菜单。当您单击菜单标题时,同样的应用程序。
片段:
jQuery('.showIt').on('click', function(e) {
e.stopPropagation();
$('.showMeHideMe').show();
console.log('.showIt clicked');
});
jQuery(document).on('click', ':not(.showIt)', function(e) {
e.stopPropagation();
$('.showMeHideMe').hide();
console.log(this.tagName + ' clicked');
});<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="showMeHideMe" style="display:none;">Example</div>
<div class="showIt">Show it!</div>
https://stackoverflow.com/questions/41202929
复制相似问题