所以有一个左侧垂直菜单。它有一个小选项按钮。单击时,它应该打开一个 div,其中有各种过滤器选项。现在,我需要它在单击时出现,并在再次单击选项按钮或用户单击 div 之外的任何位置时消失。
所以我有以下代码。
//options filter menu animation
$('#optionsmenu').hide(); //hides the menu
$('.optionsfilters').click(function(e){
var $this = $('#optionsmenu');
$this.show();
var left = $('#sidebar').css('width'),
top = $(this).offset().top;
$this.css('top', top);
$this.css('left', left);
});
$(':not(.optionsfilters)').click(function(e){
$('#optionsmenu').hide();
});
HTML 是
<div id="sidebartitle">
<h2>Organisation</h2>
<a id="optionsfilters" class="optionsfilters">Options</a>
</div>
<div id="optionsmenu" class="optionsfilters">
<h3>Add New</h3>
<ul>
<label>Year</label>
<select>
<option>2000</option>
<option>2001</option>
<option>2002</option>
<option>2003</option>
<option>2004</option>
<option>2005</option>
</select>
</ul>
</div>
它不能一起工作,即两个 javascript 函数,当第二个函数被注释掉时,第一个函数单独工作。如果我注释掉隐藏部分并添加一条警报消息,第二个就可以了。但它们放在一起就不起作用了。
有什么冲突吗?
最佳答案
好的,您需要做一些事情:
1) 如果您希望原始按钮关闭菜单,您将需要使用 .toggle()
而不是 .show()
2) 您将需要检测文档上的单击,以隐藏选项菜单。如果由于 e.stopPropagation();
(下面的第 4 点)而单击了选项菜单,则不会调用该函数。
$(document).click(function() {
$('#optionsmenu').hide();
});
3) 您还需要检查(因为两者具有相同的类)所单击的 .optionsfilters
不是过滤器本身(否则这将阻止您单击选项)。
if( e.target !== this ) {
return;
}
4) 使用 e.stopPropagation();
停止事件向上冒泡到父级(或文档)。
这应该是您正在寻找的:
$('#optionsmenu').hide(); //hides the menu
$('.optionsfilters').click(function(e){
e.stopPropagation();
if( e.target !== this ) {
return;
}
var $this = $('#optionsmenu');
$this.toggle();
var left = $('#sidebar').css('width'),
top = $(this).offset().top;
$this.css('top', top);
$this.css('left', left);
});
$(document).click(function() {
$('#optionsmenu').hide();
});
这是工作 fiddle :http://jsfiddle.net/lee_gladding/pny4vq26/
关于javascript - 这段代码有什么问题,尝试点击菜单吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27169042/