[英]how to change border color on click
當我點擊顏色“red”、“hotpink”、“greenyellow”、“tomato”、“lightcoral”、“lightblue”時,我想以隨機順序更改顏色:
function changeColor() {
document.getElementById("box").style.borderColor=red", "hotpink", "greenyellow ", "tomato", "lightcoral", "lightblue"
這里的所有其他答案似乎都在生成一個隨機索引,因此生成的顏色始終是隨機的。
要以隨機順序更改顏色,請使用Fisher-Yates(又名 Knuth)隨機播放顏色數組並使用變量來跟蹤索引。
var colors = shuffle(["red", "hotpink", "greenyellow ", "tomato", "lightcoral", "lightblue"]); var i = 0; function changeColor() { document.getElementById("box").style.borderColor = colors[i]; if (colors.length - 1 == i) { i = 0; } else { i++; } } function shuffle(r){for(var f,n=r.length;0!==n;)f=Math.floor(Math.random()*n),n--,[r[n],r[f]]=[r[f],r[n]];return r}
#box { height: 50px; width: 50px; border: 10px solid; }
<div id="box"> </div> <button onclick="changeColor()">Change</button>
您可以使用 JavaScript Math.random()
函數。
function changeColor(){ var colors = ['red', 'green', 'blue', 'orange', 'yellow']; document.getElementById("box").style.borderColor = colors[Math.floor(Math.random() * colors.length)]; }
#box{ border: 1px solid black; height:100px; margin: 0 auto; } #box:hover{ cursor:pointer }
<div id="box" onclick="changeColor();"> <div>
const div = document.getElementById("a"); const colorArr = ["red", "green", "blue", "orange", "yellow"]; function changeColor() { // grab a color from the array ; // step one grab a random index from the array or colorArr let index = Math.floor(Math.random() * (colorArr.length + 1)); // console.log(index); div.style.borderColor = colorArr[index] } function changeColor2() { const randomColor = Math.floor(Math.random()*16777215).toString(16); div.style.borderColor = "#" + randomColor // https://www.w3schools.com/jsref/jsref_tostring_number.asp }
#a{ border: 25px solid red; width: 235px; height: 235px; display: flex; background-color: "black" }
<div id="a"> </div> <button onclick = "changeColor()"> Click me </button> <button onclick = "changeColor2()"> More Random Colors </button>
let colors = ["red", "hotpink", "greenyellow ", "tomato", "lightcoral", "lightblue"];
function changeColor() {
document.getElementById("box").style.borderColor=colors[Math.floor(Math.random()*colors.length)];
}
我建議將顏色放入數組並生成 0-4 之間的隨機數並獲取該數組元素。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.