简体   繁体   English

使用 if 条件在 JavaScript 中切换添加和删除类

[英]Toggle add and remove class in JavaScript with if condition

I have a element with an id="caretToggle" and a button with onclick="caretToggle()".我有一个带有 id="caretToggle" 的元素和一个带有 onclick="caretToggle()" 的按钮。 This fires a function that adds a class to invert the caret on the button.这将触发一个函数,该函数添加一个类来反转按钮上的插入符号。

I am successful in running:我成功运行:

function caretToggle() {
  var caretElement = document.getElementById("caretToggle");
  caretElement.classList.add("dropup");
}

But This leaves the caret inverted after the collapse is closed.但是,在折叠关闭后,这会使插入符号倒置。 I want to toggle the caret once the button is clicked again.再次单击按钮后,我想切换插入符号。

This is my condition code that I have failed to get working:这是我无法正常工作的条件代码:

function caretToggle() {
  var caretElement = document.getElementById("caretToggle");
  if (caretElement.classList.contains("dropup")) {
    caretElement.classList.remove("dropup");
  } else {
    caretElement.classList.add("dropup");
  }
}

Thank you in advance for any help you may provide!预先感谢您提供的任何帮助!

You dont need to check wheter contains or not.您不需要检查是否包含。 What you can do simply use toggle function on classList :)您可以简单地在classList上使用toggle功能:)

function caretToggle() {
  var caretElement = document.getElementById("caretToggle");
  caretElement.classList.toggle("dropup");
}

And also there is a conditional toggle like:还有一个条件切换,如:

caretElement.classList.toggle("dropup", counter < 10)

Check here from MDN从 MDN 检查这里

If you want to toggle class simply do it like this如果您想切换课程,只需这样做

 let caretElement = document.getElementById("caretToggle"); function caretToggle() { caretElement.classList.toggle("dropup"); console.log('class attribute contains: ', caretElement.className) }
 span { margin:10px; } .dropup { background-color: purple; padding: 1em; border-radius: 10px; color: white; }
 <span id="caretToggle">HTMLElement</span> <br/> <br/> <br/> <br/> <button onclick="caretToggle()">Click</button>

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

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