简体   繁体   中英

Problem with EventListener to create a RGB color palette with JS

i'm trying to create a palette of color with 2 block. My problem is that my code give me thoose blocks with the same color, how can i separate the two to make two distinct color? I hope i am clear my english is not that good. Thanks in advance!

 const button = document.querySelector("button"); const blockone = document.querySelector("#block1"); const blocktwo = document.querySelector("#block2"); button.addEventListener("click", function() { const r = Math.floor(Math.random() * 255); const g = Math.floor(Math.random() * 255); const b = Math.floor(Math.random() * 255); const newColor = `rgb(${r}, ${g}, ${b})` blockone.style.backgroundColor = newColor; blockone.innerText = newColor const r2 = Math.floor(Math.random() * 255); const g2 = Math.floor(Math.random() * 255); const b2 = Math.floor(Math.random() * 255); const newColor2 = `rgb(${r}, ${g}, ${b})` blocktwo.style.backgroundColor = newColor2; blocktwo.innerText = newColor2 })
 <div id="block1"></div> <div id="block2"></div> <button>click</button>

You have a typo in your code. Replace 'const newColor2 = rgb(${r}, ${g}, ${b}) ' with 'const newColor2 = rgb(${r2}, ${g2}, ${b2}) '

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