简体   繁体   English

如何检测元素外部的点击,但该元素生了孩子

[英]How to detect a click outside an element, but that element got children

I know this question might be repetitive as I have seen this solution: How do I detect a click outside an element? 我知道这个问题可能是重复性的,因为我已经看到了以下解决方案: 如何检测元素外部的单击?

I want to remove #main-element if I click outside the element, BUT, that element also has child elements inside. 如果要在元素外部单击,但要删除#main-element,则该元素内部也包含子元素。 Meaning, if I click one of the child of #main-element, #main-element should not close 意思是,如果我单击#main-element的子级之一,则#main-element不应关闭

<div id="main-element">
    <div class="test">1</div>
    <div class="test">2</div>
    <div class="test">3</div>
    <div class="test">4</div>
</div>

I tried using this solution: 我尝试使用此解决方案:

$('html').click(function(e){
    if(e.target.id !== 'main-element') {
       $("#main-element").removeClass("open").hide();
    }
});

// For the trigger
$("#click-show").click(function(){
    if($("#main-element").hasClass("open"))
    {
       $("#main-element").removeClass("open").hide();
    }
    else{
       $("#main-element").addClass("open").show();
    }
});

This might help: 这可能会有所帮助:

DEMO DEMO

Use closest to loop through parents and classes to show/hide your element; 使用最接近来遍历父级和类以显示/隐藏您的元素;

$('html').on('click', function(){
  var mainElement = $('#main-element');
  if($(this).closest(mainElement).length){
      return;
  }
  mainElement.addClass('main-element-closed')
}) 
$('*').click(function(){
if($(this).has('#main-element') || $(this).parent().has('#main-element')){
// it will open here
}else{
//put your hide code
}
});

尝试使用jquery.click(document)来指代jquery的功能是HasClass('your child element class')

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM