我正在尝试(没有成功)创建一个复选框,该复选框在选中时会更改正文的某些样式属性,如下所示:
<script>
const x = document.getElementById('y');
if (x.checked == true) {
document.body.style.setProperty('property', 'value');
} else {
document.body.style.setProperty('property', 'value');
}
</script>
我做错了什么? 🤔
提前致谢!
最佳答案
您需要使用事件监听器并在监听器中运行该脚本。您在代码中所做的是在脚本运行时设置一次颜色,您没有告诉程序在每次更改复选框时都进行检查。
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" />
关于javascript - 使用 JavaScript 选中复选框时更改样式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54872270/