简体   繁体   English

toggleClass 不起作用,但 addClass 起作用

[英]toggleClass does't work, but addClass does

I have imported jQuery and Bootstrap in my HTML page already.我已经在我的 HTML 页面中导入了 jQuery 和 Bootstrap。

Anyhoo, I wanted to toggle a dropdown menu once I click on the little menu image. Anyhoo,我想在单击小菜单图像后切换下拉菜单。

Here's how I hide my menu dropdown:这是我隐藏菜单下拉菜单的方法:

.menu {
  height:150px;
  width:155px;
  background-color:black;
  border-radius:5px;
  position:absolute;
  top:-10px;
  left:100%;
  padding-left:0;
}
.menu-active {
  position:absolute;
  top:35px;
  left:60%;
}

To make it responsive, I first tried addClass (menuBtn is the button image and I got):为了使它具有响应性,我首先尝试了addClass (menuBtn 是按钮图像,我得到了):

$('.menuBtn').click(function(){
  $('.menu').addClass('menu-active');
})

Which works pretty smooth, though it's always ignored if I added time like addClass('menu-active', 1000) , but this is a minor problem!它的工作非常顺利,尽管如果我添加时间像addClass('menu-active', 1000) ,它总是被忽略,但这是一个小问题! I want to make it toggle, so I tried to change it to toggleClass :我想让它切换,所以我尝试将其更改为toggleClass

$('.menuBtn').click(function(){
  $('.menu').toggleClass('menu-active');
})

Even when I intended to bypass toggle and just use if like:即使我打算绕过切换并使用if like:

function menuDropdown(){
$('.menuBtn').on('click', function(){
 if($('.menu').hasClass('menu-active')){
  $('.menu').removeClass('menu-active');
  }else{
    $('.menu').addClass('menu-active');
 });
}

Both of these don't work, the website just ignored them thoroughly.这两个都不起作用,网站只是彻底忽略了它们。 I know bootstrap does have a simpler way to do this, I just wanna see what can I write on my own.我知道 bootstrap 确实有一个更简单的方法来做到这一点,我只是想看看我自己能写些什么。

Here is one way to solve the problem.这是解决问题的一种方法。 Create an ID and use that to refer to your menu instead of trying to use the menu class:创建一个 ID 并使用它来引用您的菜单,而不是尝试使用菜单类:

HTML: HTML:

<div id="toggler" class="menu">Menu Example</div>
<button type="button" class="menuBtn">Click me</button>

JQuery:查询:

$('.menuBtn').click(function () {
        $('#toggler').toggleClass('.menu-active menu');
 });

Notice how the above toggles both the .menu-active and the .menu class based off of the #toggler ID.注意上面是如何根据 #toggler ID 切换 .menu-active 和 .menu 类的。

A working example: http://jsfiddle.net/gratiafide/vubsv2pt/12/一个工作示例: http : //jsfiddle.net/gratiafide/vubsv2pt/12/

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

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