【问题标题】:JavaScript: Why doesnt classList.remove work? [duplicate]JavaScript:为什么 classList.remove 不起作用? [复制]
【发布时间】:2021-04-01 19:40:51
【问题描述】:

这是代码的一部分,其中函数 lightOn 必须在 decorLight 拥有类 'light-on' 时删除它。 Idk,但它根本不工作......上面有类似的功能。

document.addEventListener("DOMContentLoaded", function(event) {
document.documentElement.setAttribute("data-theme", "light");

const themeSwitcher = document.getElementById("theme-switcher");
const decorLight = document.getElementById("decorLight");

function transformSwitcher() {
    if (themeSwitcher.className == 'pressed')
        themeSwitcher.classList.remove('pressed');
    else themeSwitcher.classList.add('pressed');
}

function lightOn() {
    if (decorLight.className == 'light-on') 
        decorLight.classList.remove('light-on');
    else decorLight.classList.add('light-on');
}

themeSwitcher.onclick = function () {
    transformSwitcher();
    lightOn();
    let currentTheme = document.documentElement.getAttribute("data-theme");
    let switchToTheme = currentTheme === "dark" ? "light" : "dark";
    document.documentElement.setAttribute("data-theme", switchToTheme);
};
});

【问题讨论】:

  • 如果元素有多个类,decorLight.className将不等于light-on
  • 请发帖minimal reproducible example。您可以使用Stack Snippet 使其可执行。
  • 如果你想切换一个类(意思是如果它不存在则放置它,如果它存在则删除它),JS 为你准备了classList.toggle('light-on')
  • 我很确定浏览器开发人员在发布代码之前已经很好地测试了他们的代码,并且classList.remove 可以按预期工作。注意还有一个classList.contains函数...
  • @Barmar 也许指出 OP 在这种情况下需要做classList.contains('light-on')

标签: javascript jquery class


【解决方案1】:

那是因为您正在检查classNameclassName 可以有多个类。

只需检查您的班级

if (themeSwitcher.classList.contains('pressed')
if (decorLight.classList.contains('light-on')

您还可以使用以下方式切换课程:

themeSwitcher.classList.toggle('pressed')

并保存 if 条件。

您可以在此处了解有关classList API 的更多信息:

https://developer.mozilla.org/en-US/docs/Web/API/Element/classList

【讨论】:

    猜你喜欢
    • 2021-08-03
    • 2014-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-01-24
    • 2013-03-05
    • 2012-10-01
    • 2014-07-07
    相关资源
    最近更新 更多