我在jquery中有这个功能,通过切换类来显示和隐藏选项'显示'。
$('#button').click(function(){
$('#dropDownMenu').find('.option').toggleClass('showing', 500, "easeOutSine");
});
CSS:
#dropDownMenu .option{
height: 0px;
}
#dropDownMenu .option.showing{
height: initial;
padding: 25px;
}
HTML:
<button id="button"></button>
<div id="dropDownMenu">
<div class="option">OP1</div>
<div class="option">OP2</div>
<div class="option">OP3</div>
<div class="option">OP4</div>
<div class="option">OP5</div>
</div>
如何通过点击页面外的任何其他位置来隐藏菜单?
答案 0 :(得分:2)
您是否尝试过使用.focusout()
事件监听器?
你可以这样试试
$('#button').focusout(function(){
$('#dropDownMenu').find('.option').removeClass('showing', 500, "easeOutSine");
});
答案 1 :(得分:1)
使用文档单击并隐藏下拉列表。只需为元素添加条件,以便它不会触发元素单击
$(document).click(function(event){
if (!event) { var event = window.event; }
var S = event.srcElement ? event.srcElement : event.target;
If(($(S).attr('id')!='dropDownMenu')||$(S).hasClass('option')==false)
{
$('#dropDownMenu').hide();
}
})
答案 2 :(得分:0)
添加$('body').click(function(e) {
以处理整个文档正文中的点击次数
$('body').click(function(e) {
if($('#dropDownMenu').find('.option').hasClass('showing')) {
if (e.target == $('#button')[0] || e.target == $('#dropDownMenu')[0]) e.preventDefault();
else
$('#dropDownMenu').find('.option').removeClass('showing', 500, "easeOutSine");
}
});
$('#button').click(function(e) {
e.preventDefault();
$('#dropDownMenu').find('.option').toggleClass('showing', 500, "easeOutSine");
});
#dropDownMenu .option {
height: 0px;
display:none;
}
#dropDownMenu .option.showing {
height: initial;
display:block;
padding: 25px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="button">menu</button>
<div id="dropDownMenu">
<div class="option">OP1</div>
<div class="option">OP2</div>
<div class="option">OP3</div>
<div class="option">OP4</div>
<div class="option">OP5</div>
</div>
答案 3 :(得分:0)
$(document).ready(function() {
$('.menu > li').click(function() {
var t = $(this);
if ( !t.hasClass('active') ) {
t.addClass('active').next('.submenu').addClass('active');
} else {
t.removeClass('active').next('.submenu').removeClass('active');
}
});
$('html').click(function(event) {
var e = $(event.target);
if ( e.parents('.submenu').length < 1 && e.next('.submenu').length < 1 ) {
$('.submenu').removeClass('active');
}
});
});
&#13;
.submenu {
display: none;
}
.submenu.active {
display: block;
}
.menu > li {
cursor: pointer;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<ul class="menu">
<li class="submenu-link">Menu Item</li>
<ul class="submenu">
<li>SubMenu Item</li>
</ul>
</ul>
&#13;
如果目标活动没有父级&#39;子菜单,则关闭下拉菜单