jQuery-在外部单击或单击另一个下拉菜单时,关闭下拉菜单/删除活动类 [英] Jquery - Close dropdown/remove active class when clicking outside or clicking another dropdown
问题描述
我刚刚创建了自己的jquery插件,并且有一个下拉菜单,可以在单击自身时切换活动"类
I just created my own jquery plugin and I have a dropdown that toggle the 'active' class when clicking itself
,我只希望在元素外部单击或单击其他下拉菜单时删除活动"类 并且每个下拉菜单都有不同的标记,但是具有相同的类,我通过调用jQuery通过以下方法将它们全部初始化:
and I just want the 'active' class to be remove when clicking outside of an element or clicking other dropdown and Every dropdown has different mark-up but with the same class and I initialized them all via jquery by calling :
$('.dropdown').dropdown();
这东西的外观类似于Bootstrap下拉列表
this thing has a similar appearance of Bootstrap dropdown
这是我的代码:
<style>
.dropdown {
position:relative;
display:inline-block;
}
.dropdown > button {
padding:6px 12px;
border-radius:4px;
border:1px solid #bbb;
background:linear-gradient(#fff 5% , #ddd 100%);
}
.dropdown.active > button,
.dropdown > button:active {
background:#ddd;
box-shadow:inset 0px 3px 6px rgba(0,0,0, 0.125);
}
.dropdown > ul {
margin:0;
list-style:none;
padding:0;
}
.dropdown > .menu {
border:1px solid #ddd;
border-radius:4px;
position:fixed;
top:65px;
display:none;
}
.dropdown > .menu li ,
.dropdown > .menu .item {
padding:6px 12px;
min-width:100px;
font-weight:bold;
}
.dropdown.active > .menu {
-webkit-transform:none;
display:inline-block;
}
</style>
<script>
(function($) {
$.fn.dropdown = function() {
var dropdown = this;
dropdown.find('button').click(function() {
$(this).parent('.dropdown').toggleClass('active');
});
}
})(jQuery);
</script>
<script>
$('.dropdown').dropdown();
</script>
<div class="dropdown">
<button>Open</button>
<div class="menu">
<div class="item">One</div>
<div class="item">Two</div>
<div class="item">Three</div>
<div class="item">Four</div>
<div class="item">Five</div>
</div>
</div>
<div class="dropdown">
<button>Open</button>
<ul class="menu">
<li>One</li>
<li>Two</li>
<li>Three</li>
<li>Four</li>
<li>Five</li>
</ul>
</div>
推荐答案
您可以先关闭所有希望单击的下拉列表,然后再激活/打开当前单击的下拉列表:
You can first close all drop downs expect clicked one, then active/open currently clicked drop down:
var p = $(this).parent();
$('.dropdown').not(p).removeClass('active');
在外部单击时关闭下拉菜单:
to close drop downs when clicked outside:
$(window).click(function() {
$('.dropdown').removeClass('active');
});
为防止通过上述代码包含下拉菜单:
And to prevent including drop down itself by above code:
$('.dropdown').click(function(event){
event.stopPropagation();
});
这是一个演示: https://jsfiddle.net/huvzb305/3
这篇关于jQuery-在外部单击或单击另一个下拉菜单时,关闭下拉菜单/删除活动类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!