javascript - 如何通过单击任意位置但排除内容本身来关闭内容?

标签 javascript jquery popup

当我点击内容本身时,我无法使内容保持打开状态。当我单击触发它的按钮以及在任何地方单击它时(这是正确的),它都会关闭。我以文档为目标,因为我将根据不同的标签元素拥有不同的功能。

如何防止点击内容本身时内容关闭?

enter image description here

JsFiddle

Javascript

$( document ).on( "click", function( event ) {

// Add internal reference
$( ".target-2" ).addClass( "gStarter" );
$( ".content-col" ).addClass( "gColumn" );


// Check if the elem been clicked has target-2 as class
// and if the tag name matches a button tag
if( $(event.target).hasClass( "target-2" ) && $( event.target ).prop( 'tagName' ) == "BUTTON" ){

    // Add active class if it doesn't have it
        if( ! $( ".target-2" ).parent().next().children().hasClass( "active" ) ){

            // Make sure there won't be any content activated
                    //$( ".gColumn" ).removeClass( "active" );
        //$( ".gStarter" ).removeAttr( "data-starter" );
        // Add active class
        $( ".target-2" ).parent().next().children().addClass( "active" );     
  } else {
      /*
       * Already have active class
       */

      // Hide content by removing the class
      $( ".target-2" ).parent().next().children().removeClass( "active" );
      // Remove data-starter attribute
      $( ".target-2" ).removeAttr( "data-starter" );
    }

} else {

  // Find and get the first class by targeting its data-starter attribute
  //var find = $('[data-starter="starter-active"]');
 // var getClass = $(find).attr('class').toString().split(' ')[0];


  if ( ! $( ".target-2" ).closest().parent().next().children().is( event.target )) {

    if ( $( ".target-2" ).parent().next().children().is(':visible')) {

      $( ".target-2" ).parent().next().children().removeClass( "active" );
    }
  }     

}

});

HTML

<div class="host">
 <div class="btn-container">
   <button type="button" data-starter="starter-active" class="target-2 target">Click here</button>
 </div>
 <div class="button-row row">
   <div class="button-col content-col">
     <span>This content is triggered by a button - ID: 13</span>
   </div>
 </div>
</div>

最佳答案

使用 closest('.contentClassName')返回(如果目标位于该内容类中)

$( document ).on( "click", function( event ) {

    if($(event.target).closest('.button-row').length){
       return; /// don't go any further
    }
    // other code is same

DEMO

关于javascript - 如何通过单击任意位置但排除内容本身来关闭内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48449832/

相关文章:

javascript - 子窗口更改父位置时的客户端事件?

javascript - 在 ES6 中处理 undefined variable 或属性

javascript - 更改窗口位置 Jquery

jquery - 使用下一个/上一个箭头加入导航 - Jquery

jquery - 是否可以通过 jquery 将 css 添加到现有的 css 类?

javascript - Firefox 没有在周围的 div 上注册点击事件

javascript - 弹窗使用knockout js

javascript - 捕获错误时如何返回明确的响应?

javascript - 如何完成从下划线模板到 mustache 的For-Each循环

c# - 单击按钮时弹出