[英]trying to close dropdown menu when dropdown menu is open and user clicks document
我试图隐藏我的下拉菜单,当用户点击其打开状态外,我使用标志isActive
,确定菜单是否打开然后我在文档上添加了一个点击事件,如果打开和停止隐藏菜单单击菜单上的传播。 现在,当我点击我的下拉锚标签时,会触发文档点击事件。 任何人都可以建议我如何解决这个问题?
JS
//User profile share tooltip
$('.btn-social-share').on('click', function(e){
e.preventDefault();
if( !isActive ){
$('.social-share-options').show();
isActive = true;
} else {
$('.social-share-options').hide();
isActive = false;
}
});
/* Anything that gets to the document
will hide the dropdown */
$(document).on('click', function(){
if( isActive ){
$('.social-share-options').hide();
isActive = false;
}
});
/* Clicks within the dropdown won't make
it past the dropdown itself */
$('.social-share-options').click(function(e){
e.stopPropagation();
});
创建一个条件,检查点击的内容是否在下拉列表中,然后隐藏下拉列表,如果点击的内容不在下拉列表中:
$(document).on('click', function(e){
if( isActive && $(e.target).closest('.social-share-options').length === 0 ){
$('.social-share-options').removeClass('is-active');
isActive = false;
}
});
我没有测试过,但我认为你需要添加e.stopPropagation()
,这会阻止你的事件冒泡:
$('.btn-social-share').on('click', function(e){
e.preventDefault();
e.stopPropagation();
//...
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.