简体   繁体   中英

how to change border color on click

I want to change colors in a random order when I click with that colors "red", "hotpink", "greenyellow", "tomato", "lightcoral", "lightblue":

function changeColor() {
     document.getElementById("box").style.borderColor=red", "hotpink", "greenyellow ", "tomato", "lightcoral", "lightblue" 

All the other answers here seem to be generating a random index so the generated color is always random.

To change the color in a random order , shuffle the array of colors using the Fisher-Yates (aka Knuth) Shuffle and use a variable to keep track of the index.

 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>

You can JavaScript Math.random() function.

 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 之间的随机数并获取该数组元素。

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM