如何在单击页面上的任何位置时从元素中删除类?

时间:2017-07-26 17:21:56

标签: javascript jquery html css

我试图在点击页面上的任何地方时隐藏元素但是div,如果你在div上点击,那么它应该切换该类。

jQuery -

 $('.onclick-dropdown-link').on('click', function(e) {
     e.preventDefault();
     var $this = $(this);
     var id = $this.attr('href');
     $('.onclick-dropdown').not(id).removeClass('open');
     $(id).toggleClass('open');
 });

HTML -

<a class="onclick-dropdown-link" href="#test-div"></a>
<div id="test-div" class="onclick-dropdown">
    <p>Lorem Ipsum<p>
</div>

CSS -

.onclick-dropdown {
    opacity: 0;
    visibility: hidden;
    z-index: 999;
}
.onclick-dropdown.open {
    opacity: 1;
    visibility: visible;
}

已经尝试过以下方法 -

$(document).on('click', function() {
    $('.onclick-dropdown').not(id).removeClass('open');
});

$(document).on('click', function() {
    $('.open').not(id).removeClass('open');
});

$('.onclick-dropdown-link').on('click', function() {
       e.stopPropagation(); // This is the preferred method.
return false;  ;
});

$(document).on('click', function() {
    $('.onclick-dropdown.open').removeClass('.open');
});

2 个答案:

答案 0 :(得分:0)

在这一行:

$('.onclick-dropdown-link').on('click', function() {
  e.stopPropagation(); // This is the preferred method.
  return false;
});

您忘了将$event传递给您的函数。它应该是这样的:

$('.onclick-dropdown-link').on('click', function(e) {
  e.stopPropagation(); // This is the preferred method.
  return false;
});

并且此代码应该有效。

工作小提琴:http://jsfiddle.net/cfgr9/540/

答案 1 :(得分:0)

您可以使用解决方案https://jsfiddle.net/t3y5zo2t/

&#13;
&#13;
$('.onclick-dropdown-link').on('click', function(e) {
   e.preventDefault();
   e.stopPropagation();
   var $this = $(this);
   var id = $this.attr('href');
   $('.onclick-dropdown').not(id).removeClass('open');
   $(id).toggleClass('open');
});

$('body:not(.onclick-dropdown-link)').click(function(e){
  $('#test-div').removeClass('open');
});
&#13;
.onclick-dropdown {
    opacity: 0;
    visibility: hidden;
    z-index: 999;
}
.onclick-dropdown.open {
    opacity: 1;
    visibility: visible;
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<body>
<a class="onclick-dropdown-link" href="#test-div">test</a>
<div id="test-div" class="onclick-dropdown">
    <p>Lorem Ipsum<p>
</div>
</body>
&#13;
&#13;
&#13;