javascript - 如果盒子是特定颜色的,我如何更改它的颜色?
问题描述
我是 JavaScript 新手,目前正在尝试一些东西。无论如何,我正在制作一个简单的盒子来改变onclick
按钮的颜色。答案很简单,但我就是想不通。到目前为止,这是 HTML:
var btn = document.getElementById("btn");
var box = document.getElementById("box");
function changeColor() {
box.style.backgroundColor = "red";
}
function ifColor() {
if (box.style.backgroundColor == "red") {
box.style.backgroundColor = "blue";
}
}
#box {
width: 200px;
height: 200px;
border-style: solid;
border-width: 0.5px;
}
<div id="box"></div>
<button id="btn" onclick="changeColor(); ifColor();">
Change box color
</button>
当我按下按钮时,它只会变成蓝色,当我再次按下它时,没有任何反应。如果我删除该ifColor
功能,该按钮只会使框变为红色。
解决方案
只需使用一种切换颜色的功能。
var btn = document.getElementById("btn");
var box = document.getElementById("box");
function changeColor() {
if (box.style.backgroundColor == "blue") {
box.style.backgroundColor = "red";
} else {
box.style.backgroundColor = "blue";
}
}
#box {
width: 200px;
height: 200px;
border-style: solid;
border-width: 0.5px;
}
<div id="box"></div>
<button id="btn" onclick="changeColor();">
Change box color
</button>
推荐阅读
- android - 为什么连续添加多个空格时,使用字符串创建的位图的空格宽度会变短?
- android - 如何使 Ionic Toast 与屏幕阅读器更兼容
- python - InvalidArgumentError:不兼容的形状:[32] 与 [8] - Keras 迁移学习
- c# - 在 C# 中执行异步操作的正确方法
- spring - 将 SSL 添加到 sprint 引导
- c - C自动定义数组大小
- bash - 在测试函数中使用参数调用bash函数
- c# - Xamarin Forms 使用时不显示新页面
元素和SDK - python - 解析 txt 文件并根据列表提取特定部分
- javascript - 错误 缺少参数。您必须指定位置。(如何为附近搜索添加监听器)