简体   繁体   English

如何在单击时向div添加类,并通过单击页面上的其他位置删除该类

[英]How to add a class to a div on click, and remove the class by clicking elsewhere on the page

I would like to expand a div, filters , when filtertoggle is clicked. 我想扩大一个div, filters ,当filtertoggle被点击。 I would like to do this by adding the class on to filters . 我想通过添加类来做到这一点on ,以filters Then, when the user clicks anywhere else on the page, I would like to remove the on class, thereby closing filters . 然后,当用户点击其他地方的页面上,我想删除on类,从而关闭filters

Here is the code I have attempted: 这是我尝试过的代码:

jQuery(document).ready(function($) {

$('body').click(function(evt) {
  if (evt.target.attr('class').includes('filtertoggle')) {
    $(this).toggleClass('on');
    $('.filters').slideToggle(200);
    return;
  } else {
    $(this).element.className = element.className.replace(/\bon\b/g, "");
    return;
  });

As it stands, filters does not open. 就目前而言, filters器无法打开。

Your logic has a couple of issues. 你的逻辑有几个问题。 Firstly, evt.target is an Element object, not a jQuery object, so it has not attr() method. 首先, evt.target是一个Element对象,而不是一个jQuery对象,所以它没有attr()方法。 You need to wrap it in a jQuery object to make that work. 您需要将其包装在jQuery对象中以使其工作。 Then you can use hasClass() to check what class is on the target . 然后,您可以使用hasClass()来检查target上的类。

Also a jQuery object has no element property, so element.className will cause a syntax error. 此外,jQuery对象没有element属性,因此element.className将导致语法错误。 You can just use removeClass() in that case. 在这种情况下你可以使用removeClass() Try this: 尝试这个:

 $('body').click(function(evt) { if ($(evt.target).hasClass('filtertoggle')) { $('.filtertoggle').addClass('on'); $('.filters').slideToggle(200); } else { $('.filtertoggle').removeClass('on'); $('.filters').slideUp(200); } }); 
 body, html { height: 100%; } .on { color: #C00; } .filters { display: none; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="filtertoggle"> FilterToggle </div> <div class="filters"> Filters... </div> 

You should also note that it may be possible to achieve this in CSS alone, depending on how your HTML is structured. 您还应该注意,单独使用CSS可能会实现此目的,具体取决于HTML的结构。 You can use the :focus selector to do it, like this: 您可以使用:focus选择器来执行此操作,如下所示:

 body, html { height: 100%; } .filtertoggle { outline: 0; } .filters { opacity: 0; transition: opacity 0.3s; } .filtertoggle:focus { color: #C00; } .filtertoggle:focus + .filters { opacity: 1; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script> <div class="filtertoggle" tabindex="1"> FilterToggle </div> <div class="filters"> Filters... </div> 

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

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