javascript - 如何阻止随机颜色重复?
问题描述
单击时标题会随机更改颜色,但它经常重复相同的颜色(我不希望它连续两次在数组中重复相同的颜色)。我试图用 if 语句解决这个问题,但我不确定为什么它不起作用。
var title = document.querySelector(".title");
function changeColor() {
let newArray = ["DarkSalmon", "LightSalmon", "Crimson", "Red",
"DeepPink", "YellowGreen", "GhostWhite"
];
let random = Math.floor(Math.random() *
Math.floor(newArray.length - 1));
console.log(random);
if (title.style.color !== newArray[random]) {
title.style.color = newArray[random];
}
}
title.addEventListener("click", changeColor);
<h1 class='title'>Berserk</h1>
解决方案
这将使每种颜色仅被选择一次。使用完所有颜色后,将刷新列表,以便可以再次随机选择所有颜色,依此类推。
// Identifies header element & defines initial colors array and colors array
const header = document.getElementsByClassName("title")[0];
const initialColors = ["DarkSalmon", "LightSalmon", "Crimson", "Red", "DeepPink", "YellowGreen"];
let colors = [];
// Calls `changeColor` when the header is clicked
header.addEventListener("click", changeColor);
// Defines the `changeColor` function
function changeColor(){
// Remembers the most recent color (formatted as lower-case)
let previousColor = header.style.color.toLowerCase();
// Makes all colors available whenever no colors are left (including on first click)
if(colors.length === 0){
// Copies the `initialColors` array, and returns the copy
// (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice)
colors = initialColors.slice();
}
// Cuts a random color out of the colors array
let newColor = removeRandFrom(colors);
// If removed color happens to match previous color, forces an additional change
// (Can only ever happen immediately after the `colors` array has been replenished)
if(newColor === previousColor){
newColor = removeRandFrom(colors);
}
// Sets text color to whichever color was just randomly removed
header.style.color = newColor;
}
// Defines the `removeRandFrom` helper function
function removeRandFrom(arr){
// Gets a psuedo-random number
const index = Math.floor(Math.random() * arr.length);
// Removes and returns the element at the randomly selected index
// (See https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/splice)
return arr.splice(index, 1);
}
<h1 class='title'>Berserk</h1>
推荐阅读
- css - 为什么 setDecorations 将 TextEditorDecorationType 分为 ViewLines 和 ViewOverlays?
- python - 我找不到我的 python selenium 程序的不和谐文本消息框的类名,我应该使用什么?
- xcode - 如何删除 xcode CompileC 命令参数
- python - Python中的CSV到JSON质量转换器
- javascript - 使用javascript将单独数组的结果转换为一个对象
- javascript - Firestore 更新嵌套对象
- flutter - 可以使用 Restoration API 将状态恢复到 Page Routes 吗?
- autofixture - 自动修复子列表示例
- python - 如何使用 reddit API 在树形结构中获取 subreddit 上的所有评论?
- node.js - 发布 req.body 始终是空对象