您好我想使用一個數組來改變顏色。我想用一個參數爲數字創建一個名爲ChangeColor(num)的函數,並使用函數來改變框的顏色,所以當點擊按鈕時,它調用該函數併發送正確的數字,以便「框」。 style.backgroundColor = arrName [num];「下面是我到目前爲止。使用數組來改變顏色
<!DOCTYPE html>
<html>
<head>
<style>
#box {
width:200px;
height:200px;
background-color:black;
}
</style>
</head>
<body>
<div id="group">
<button id="blue">Blue</button>
<button id="red">Red</button>
<button id="green">Green</button>
</div>
<div id="box"></div>
<script type="text/javascript">
var colors = ["blue","red","green"];
var blue = document.getElementById("blue");
var red = document.getElementById("red");
var green = document.getElementById("green");
var box = document.getElementById("box");
var numclicks = 0;
blue.addEventListener("click", function() {
if(numclicks == 0) {
box.style.backgroundColor = colors[0];
}
});
red.addEventListener("click", function() {
if(numclicks == 0) {
box.style.backgroundColor = colors[1];
}
});
green.addEventListener("click", function() {
if(numclicks == 0) {
box.style.backgroundColor = colors[2];
}
});
</script>
</body>
</html>
至今不太遠,你甚至沒有函數聲明。你嘗試過創建函數嗎?在那種情況下,你有什麼確切的問題來創建函數?我們可以幫助你完成作業,但你必須付出一些努力。 –
哈哈我同意。對不起,我沒有付出太多努力。我編輯了代碼,這是做這件事的理想方式嗎? – RAY
什麼*確切*是您遇到的問題? – FluffyKitten