[英]How do i change the color of a box if it was on a specific color?
我是 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>
您的代碼正在運行,只需設置幾秒鍾的延遲即可查看它的變化。
var btn = document.getElementById("btn"); var box = document.getElementById("box"); function changeColor() { box.style.backgroundColor = "red"; } function ifColor() { setTimeout(()=>{ if (box.style.backgroundColor == "red") { box.style.backgroundColor = "blue"; } },2000); }
#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>
您是否想要這樣,當您單擊按鈕時,它會在紅色和藍色之間更改顏色?
您設置代碼的方式將始終為藍色,因為:
function changeColor() {
box.style.backgroundColor = "red";
}
function ifColor() {
if (box.style.backgroundColor == "red") {
box.style.backgroundColor = "blue";
}
}
你首先調用 changeColor(); 將按鈕變為紅色,然后運行 ifColor() 將按鈕變為藍色。 這幾乎是瞬間發生的。
你只需要這樣做:
function changeColor() {
if(box.style.backgroundColor === "red"){
box.style.backgroundColor = "blue";
}
else box.style.backgroundColor = "red";
}
您還可以執行以下操作:
var box = document.getElementById("box"); function changeColor() { if (box.classList.contains('red')) { box.classList.remove('red'); box.classList.add('blue'); } else { box.classList.remove('blue'); box.classList.add('red'); } }
#box { width: 200px; height: 200px; border-style: solid; border-width: 0.5px; } .red { background-color: red; } .blue { background-color: blue; }
<div id="box" class="red"></div> <button id="btn" onclick="changeColor();"> Change box color </button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.