当我点击内容本身时,我无法使内容保持打开状态。当我单击触发它的按钮以及在任何地方单击它时(这是正确的),它都会关闭。我以文档为目标,因为我将根据不同的标签元素拥有不同的功能。
如何防止点击内容本身时内容关闭?
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
关于javascript - 如何通过单击任意位置但排除内容本身来关闭内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48449832/