【问题标题】:How could I restart this current function我怎么能重新启动这个当前的功能
【发布时间】:2022-01-21 23:31:12
【问题描述】:

在使用此功能期间,您单击一个按钮,该按钮将为您提供一个正方形,该正方形将在一个正方形内显示一种颜色。但是,当您单击按钮 60 次时,程序停止工作,因为所有颜色都已使用。然后我将如何重新启动此过程以便我可以继续点击?

<html>
    <head>
        <script>
            var usedColors = [];
            
            function randomColour(){
                var colour=[];
                colour[0]= '#edf2fb';
                colour[1]= '#d7e3fc';
                colour[3]= '#c1d3fe';
                colour[4]= '#d1d1d1';
                colour[5]= '#e1dbd6';
                colour[6]= '#e2e2e2';
                colour[7]= '#f9f6f2';
                colour[8]='#ffc09f';
                colour[9]='#ffee93';
                colour[10]='#fcf5c7';
                colour[11]='#a0ced9';
                colour[12]='#adf7b6';
                colour[13]='#809bce';
                colour[14]='#95b8d1';
                colour[15]='#b8e0d2';
                colour[16]='#d6eadf';
                colour[17]='#eac4d5';
                colour[18]='#e8d1c5';
                colour[19]='#eddcd2';
                colour[20]='#fff1e6';
                colour[21]='#f0efeb';
                colour[22]='#eeddd3';
                colour[23]='#e8dff5';
                colour[24]='#fce1e4';
                colour[25]='#fcf4dd';
                colour[26]='#ddedea';
                colour[27]='#daeaf6';
                colour[28]='#d3ab9e';
                colour[29]='#eac9c1';
                colour[30]='#ebd8d0';
                colour[31]='#ffe5ec';
                colour[32]='#ffc2d1';
                colour[33]='#ceb5b7';
                colour[35]='#b5d6d6';
                colour[36]='#f2f5ff';
                colour[37]='#efcfe3';
                colour[38]='#eaf2d7';
                colour[39]='#b3dee2';
                colour[40]='#f8ad9d';
                colour[41]='#fbc4ab';
                colour[42]='#ffdab9';
                colour[43]='#cdb4db';
                colour[44]='#ffc8dd';
                colour[45]='#ffafcc';
                colour[46]='#bde0fe';
                colour[47]='#a2d2ff';
                colour[48]='#fdffb6';
                colour[49]='#caffbf';
                colour[50]='#9bf6ff';
                colour[51]='#a0c4ff';
                colour[52]='#ffc6ff';
                colour[53]='#a7bed3';
                colour[54]='#c6e2e9';
                colour[55]='#f1ffc4';
                colour[56]='#ffcaaf';
                colour[57]='#dab894';
                colour[58]='#fec7bc';
                colour[59]='#fcf5ee';
  
                var pick= Math.floor(Math.random()*60);
  
                if(usedColors.includes(pick)){
                    randomColour();
                }
  
                usedColors.push(pick); document.getElementById("colorpad").style.backgroundColor = colour[pick];
                console.log(usedColors);
            }
        </script>
    </head>
    <body>
        <div id="colorpad" style="height: 300px; width: 300px;">
            <button onclick="randomColour()">btn</button>
        </div>
    </body>
</html>

【问题讨论】:

  • 简单检查usedColorsempty it的长度?
  • if(usedColors.length === 60) usedColors = []
  • 我认为你应该随机化颜色十六进制值;)stackoverflow.com/questions/5092808/…
  • @SebastianSimon usedColors 没有设置长度。
  • @Kailau05 你这是什么意思? usedColors 是一个数组。每个数组都有一个长度。

标签: javascript html function loops restart


【解决方案1】:

跟踪当前颜色:

let curr = 0;

“下一步” 按钮上单击递增curr 索引,并在模运算符% 的帮助下进行环回:

curr += 1;
curr %= colour.length; // On "next" loop back to 0 if we reached the end

你的颜色终于回到了 0

console.log(colour[curr]);    // '#edf2fb'

演示:

const EL = (sel, EL) => (EL||document).querySelector(sel);

const colors = [
  '#edf2fb',
  '#d7e3fc',
  '#c1d3fe',
  '#d1d1d1',
  '#e1dbd6',
  '#e2e2e2',
  '#f9f6f2',
  '#ffc09f',
  '#ffee93',
  '#fcf5c7',
];

const tot = colors.length;
let curr = 0;

const curr_rand = () => curr = Math.floor(Math.random() * tot);
const curr_next = () => (curr += 1, curr %= tot);
const applyColor = () => EL("body").style.background = colors[curr];

EL("#rand").addEventListener("click", () => {
  curr_rand();
  applyColor();
  console.log(curr);
});

EL("#next").addEventListener("click", () => {
  curr_next();
  applyColor();
  console.log(curr);
});
<button type="button" id="rand">Generate</button>
<button type="button" id="next">Next</button>

【讨论】:

  • 你能编辑一下代码,让我看看我应该把代码放在哪里吗?
  • @Kailau05 只需将您的整个代码替换为我的。比最终添加缺少的usedColors 逻辑...如果需要。
  • 如何将其放入正方形中 我将 div id="colorpad" style="height:300px; width:300px; 添加到代码中,但它似乎不起作用,您介意实施吗这在你的代码中,所以我可以试试。非常感谢!
  • @Kailau05 jsfiddle.net/uwyc76h1 希望对您有所帮助。这是一个非常简单的编辑。
  • 非常感谢!
【解决方案2】:

这是一个使用小型工厂函数的 sn-p,可以无限重新着色。重新着色是使用颜色数组的随机洗牌副本完成的。这样您就不必每次都检查颜色是否已被使用。

此外,请参阅 sn-p 中的 cmets。它使用event delegation 作为处理程序,因为使用内联事件处理程序通常是not a good idea

为了保持 sn-p 精简,只使用了 10 种颜色。

const colorize = randomColor(
  ['#edf2fb', '#d7e3fc', '#c1d3fe', '#d1d1d1', '#e1dbd6',
   '#e2e2e2', '#f9f6f2', '#ffc09f', '#ffee93', '#fcf5c7'] );

document.addEventListener(`click`, evt => {
  if (evt.target.id === `colorChange`) {
    return colorize(document.querySelector(`.color`));
  }
});

// randomColor is a factory function, it returns a function. 
// The function can use the inner variables as well as the 
// [colors] array from the parameter(they are 'closed over'). 
// The [colors] array is shuffled randomly (Fisher-Yates) and 
// on every call (from click) the first color from that shuffled 
// array is picked - until it's empty. If [shuffled] is empty 
// the original [color] array is reshuffled (into [shuffled]).
// This way  the coloring is restarted with a new set of 
// random colors.
function randomColor(colors){
  const shuffle = array =>
    [...Array(array.length)]
      .map((el, i) => Math.floor(Math.random() * i))
      .reduce( (a, rv, i) => 
        ([a[i], a[rv]] = [a[rv], a[i]]) && a, array.slice());
  //                                          ^ slice copies the original      
  let shuffled = shuffle(colors);
  
  // return a function
  return colorDiv => {
    const restarted = !shuffled.length;
    shuffled = shuffled.length > 0 ? shuffled : shuffle(colors);
    const nwColor = shuffled.shift();
    colorDiv.style.backgroundColor = nwColor;
    
    // for demo: color is displayed, and bold/red if [shuffled] is renewed
    colorDiv.classList[restarted ? `add` : `remove`](`restart`);
    colorDiv.dataset.color = nwColor;
  }
}
.color {
  width: 100px;
  height: 100px;
  border: 1px solid #777;
  margin: 1rem 0;
  text-align: center;
  line-height: 100px;
}

.color:before {
  content: attr(data-color);
}

.color.restart:before {
  color: red;
  font-weight: bold;
}
<div class="color"></div>

<button id="colorChange">change</button>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-12-19
    • 1970-01-01
    • 2021-02-12
    • 2021-12-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多