用一个按钮的点击事件来随机产生颜色,并用一个h3来显示动态的rgb的值
如何产生随机颜色:
Math.floor(Math.random() * 255)生成[0,255]的随机数,用rgb(r,g,b)拼接
![]()
改变按钮的背景色并在右边显示具体的rgb值。
const btn = document.querySelector('#change_color_btn');
const h3 = document.querySelector('#h3');
btn.addEventListener('click', function () {
newColor = makeRandColor();
btn.style.backgroundColor = newColor;
h3.innerText = newColor;
})
const makeRandColor = () => {
const r = Math.floor(Math.random() * 255);
const g = Math.floor(Math.random() * 255);
const b = Math.floor(Math.random() * 255);
return `rgb(${r}, ${g}, ${b})`;
}

浙公网安备 33010602011771号