简体   繁体   English

带复选框的暗模式开关按钮

[英]Dark mode on-off button with checkbox

Console.logs are not showing. Console.logs 没有显示。 And my functions are not working.而且我的功能不起作用。 I tried several different functions and solutions but none of them worked for me.我尝试了几种不同的功能和解决方案,但没有一个对我有用。 Where is the problem can anyone help?问题出在哪里,谁能帮忙?

this my html这是我的 html

<div class="switch-toggle darkmodecheckbox">
              <input type="checkbox" name="checkbox" id="darkmodeonoff" />
              <label for="darkmodeonoff"></label>
            </div>

this my js;这是我的 js;

var checkbox = document.querySelector("input[name=checkbox]");
    console.log(checkbox);

    checkbox.addEventListener("change", (e) => {
      if (e.target.checked) {
        darkmode();
        console.log("Checkbox is checked..");
      } else {
        darkmodeoff();
        console.log("Checkbox is not checked..");
      }
    });

bro where is your darkmode() and darkmodeoff() functions?兄弟你的 darkmode() 和 darkmodeoff() 函数在哪里? Try add them like at the below and check out are you gonna get any alert or not?尝试在下面添加它们,然后检查您是否会收到任何警报? Also if you see any warning on the console, please share另外,如果您在控制台上看到任何警告,请分享

 const darkmode = () =>{
        alert('dark')
    }
    const darkmodeoff = () =>{
        alert('light')
    }

Try using classList.toggle :尝试使用classList.toggle

checkbox.addEventListener("change", (e) => {
      const example = document.querySelector('.containerThatYouWantUse')
      example.classList.toggle('darkModeClass')
    });

You can let darkmode and darkmodeoff log what you want你可以让 darkmode 和 darkmodeoff 记录你想要的

const darkmode = () =>{
    console.log("Checkbox is checked..");
}
const darkmodeoff = () =>{
    console.log("Checkbox is not checked..");
}

Then call it using if statement然后使用 if 语句调用它

if (e.target.checked) {
    darkmode();
  } else {
    darkmodeoff();
  }
});

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

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