简体   繁体   中英

Change styles when checking checkbox with JavaScript

I'm trying (with no success) to create a checkbox that changes some style properties of the body when checked, something like this:

<script>
  const x = document.getElementById('y');
  if (x.checked == true) { 
    document.body.style.setProperty('property', 'value');
  } else {
    document.body.style.setProperty('property', 'value');
  }
</script>

What am I doing wrong? 🤔

Thanks in advance!

You need to use an event listener and run that script inside the listener. What you are doing in your code is setting the color once when the script is run, you haven't told the program to check every time the checkbox is changed.

 const checkBox = document.getElementById('y'); checkBox.addEventListener("change", updateBackground); updateBackground(); function updateBackground() { document.body.style.backgroundColor = checkBox.checked ? "red" : "blue"; }
 <input id="y" type="checkbox" />

You could also just a class instead and change or remove the class name.

 const checkBox = document.getElementById('y'); checkBox.addEventListener("change", updateBackground); updateBackground(); function updateBackground() { document.body.className = checkBox.checked ? "" : "blue"; }
 body { background-color: red; } body.blue { background-color: blue; }
 <input id="y" type="checkbox" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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