[英]the function only works once on button click
我正在做一個換色器項目。 我在 function 之外有可變顏色索引,但是當這個變量在外面時,它只在單擊按鈕時起作用。 當它位於 function 內部時,它工作正常,但顏色和顏色名稱不匹配
.js 文件:
let arr = [
"red", "yellow" , "green" , "blue" , "violet" , "purple" , "orange"
]
let colorIndex = parseInt(Math.random() * arr.length)
function changeColor() {
document.getElementById("body").style.backgroundColor = arr[colorIndex];
}
function changeName(){
document.getElementById("colorName").innerHTML = arr[colorIndex]
}
html 文件:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="index.css">
</head>
<body id="body">
<p id="colorName"></p>
<button id="btn" onclick="changeColor(),changeName()">Click Me</button>
<script src="index.js"></script>
</body>
</html>
我看過其他答案,但他們不回答這個
您可以創建顏色 function 並這樣做:
let arr = [
"red", "yellow" , "green" , "blue" , "violet" , "purple" , "orange"
]
function changeColor() {
document.getElementById("body").style.backgroundColor = arr[color()];
}
function color(){
let colorIndex = parseInt(Math.random() * arr.length)
return colorIndex;
}
function changeName(){
document.getElementById("colorName").innerHTML = arr[color()]
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.