javascript - 使用 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>
我究竟做错了什么?
提前致谢!
解决方案
您需要使用事件侦听器并在侦听器中运行该脚本。您在代码中所做的是在脚本运行时设置一次颜色,您没有告诉程序每次更改复选框时都要检查。
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" />
推荐阅读
- blazor - 如何在 Blazor 服务器端模拟延迟?
- ios - 基于自定义 iOS 框架覆盖本地化键值
- python - pip 安装具有不同哈希的相同模块
- python - 将元组的值加在一起
- java - Android Studio 上的 Java 计算器应用程序无法正常运行
- html - 带有弹性包装的响应式图像
- python - 如何根据列的百分位数从 DataFrame 中采样?
- azure - Azure DevOps - 如何创建个人访问令牌 (PAT) 以便为其他用户显示?
- c++ - 带有 Xcode 生成器的特定于配置的 add_custom_command
- git - ./.git-rewrite 未完成的 git filter-branch 尝试后的文件