我有一个单击DIV时打开的下拉列表:
<div class="unitwrap">
<span class="dropdown">Click this text</span>
<ul class="units">
<li>Second</li>
<li>Minute</li>
<li>Hour</li>
</ul>
</div>
$('body')
// open dropdown
.on("click", '.unitwrap', function() {
$(this).toggleClass('active');
});
.active .units { display:block }
我想设置一个事件以关闭下拉菜单,但是我不想每次单击都检查dom:
$('body').on('click', function(){ $('.unitWrap').removeClass('active') });
单击下拉元素之外的任何位置时,关闭打开的元素的最佳方法是什么?
这里是一个例子:
$('body')
// open dropdown
.on("click", '.unitwrap', function() {
$(this).toggleClass('active');
});
.unitwrap {
cursor: pointer;
background: red;
}
.unitwrap.active .units {
display: block;
}
.unitwrap .dropdown:after {
display: inline-block;
margin-left: 4px;
content: '';
border-top: 5px solid transparent;
border-top: 5px solid transparent;
border-right: 5px solid transparent;
border-left: 5px solid transparent;
}
.unitwrap .units {
font-size: 13px;
position: absolute;
z-index: 5;
display: none;
width: 140px;
margin-top: 7px;
padding: 7px 0;
text-transform: none;
border-radius: 3px;
background: #fff;
box-shadow: 0 1px 4px rgba(0, 0, 0, .13);
}
.unitwrap .units li {
font-weight: bold;
display: block;
padding: 4px 10px 4px 30px;
cursor: pointer;
color: #a8a8a8;
}
.unitwrap .units li em {
font-weight: normal;
font-style: normal;
float: right;
color: #ccc;
}
.unitwrap .units li.active {
color: #676767;
}
.unitwrap .units li.active:before {
font: 11px;
position: absolute;
left: 10px;
margin-top: 3px;
color: inherit;
}
.unitwrap .units li:hover,
.unitwrap .units li:hover em {
color: #fff;
background: #2cb6f7;
}
.unitwrap .units.active {
display: block;
}
<script src="//code.jquery.com/jquery-2.1.1.min.js"></script>
<div class="unitwrap">
<span class="dropdown">Click this text</span>
<ul class="units">
<li>Second</li>
<li>Minute</li>
<li>Hour</li>
</ul>
</div>
mouseleave
事件。 $('.unitwrap').click(function() {
$(this).toggleClass('active');
});
$(window).click(function(event){
if(!$(event.target).hasClass('active')){
$('.unitwrap').removeClass('active');
}
});