首页 > 解决方案 > 如何阻止随机颜色重复?

问题描述

单击时标题会随机更改颜色,但它经常重复相同的颜色(我不希望它连续两次在数组中重复相同的颜色)。我试图用 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>

标签: javascriptcss

解决方案


这将使每种颜色仅被选择一次。使用完所有颜色后,将刷新列表,以便可以再次随机选择所有颜色,依此类推。

// 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>

参考资料:
MDN - 切片
MDN - 拼接


推荐阅读