每個方塊都有隨機的顏色。例如,粉紅色變成綠色,橙色變成粉紅色等。如何更改背景?
<section>
<div id="one"></div>
<div id="two"></div>
<div id="three"></div>
<div id="four"></div>
<button id="btn">Click Me</button>
</section>
let colors = ["pink" , 'yellow' , 'green' , 'blue']
let btn = document.getElementById('btn')
let one = document.getElementById('one')
let two = document.getElementById('two')
let three = document.getElementById('three')
let four = document.getElementById('four')
one.style.backgroundColor = colors[0]
two.style.backgroundColor = colors[1]
three.style.backgroundColor = colors[2]
four.style.backgroundColor = colors[3]
btn.addEventListener('click' , function(){
let randomColor = colors[Math.floor(Math.random() * colors.length)]
one.style.backgroundColor = randomColor
})
然后我不明白該怎么做 圖片
uj5u.com熱心網友回復:
試試這個,使用forEach回圈更容易。
unshift每次用戶單擊時,用于將最后一個元素移動到陣列的頂部。
let colors = ["pink" , 'yellow' , 'green' , 'blue']
//Assign orginial color:
document.querySelectorAll('div').forEach((item,index)=>{
item.style.backgroundColor = colors[index]
})
document.querySelector('#btn').addEventListener("click",function(){
document.querySelectorAll('div').forEach((item,index)=>{
item.style.backgroundColor = colors[index]
})
colors.unshift(colors.splice(colors.length-1, 1)[0]);
})
<div id="one">1</div>
<div id="two">2</div>
<div id="three">3</div>
<div id="four">4</div>
<button id="btn">Click Me</button>
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/418258.html
標籤:
