首页 > 解决方案 > 使用 JavaScript 检查复选框时更改样式

问题描述

我正在尝试(没有成功)创建一个复选框,该复选框在选中时会更改主体的某些样式属性,如下所示:

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

我究竟做错了什么?

提前致谢!

标签: javascript

解决方案


您需要使用事件侦听器并在侦听器中运行该脚本。您在代码中所做的是在脚本运行时设置一次颜色,您没有告诉程序每次更改复选框时都要检查。

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" />

您也可以只使用一个类并更改或删除类名。

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" />


推荐阅读