我是初学者,想知道如何使用生成按钮生成所有不同的颜色?我应该向按钮 addEventListener 的第二个参数添加什么?
另外,如何让它在刷新时自动生成颜色而不是不生成颜色?
var getcolors = document.querySelectorAll(".palette").forEach(function(btn) {
btn.addEventListener("click", function() {
var n = Math.random();
n = n * 256;
n = Math.floor(n);
var a = Math.random();
a = a * 256;
a = Math.floor(a);
var b = Math.random();
b = b * 256;
b = Math.floor(b);
var color = "rgb(" + n + "," + a + "," + b + ")";
btn.style.backgroundColor = color;
});
});
document.getElementById("generate").addEventListener("click", function() {});
body {
text-align: center;
background-color: black;
}
.palette {
outline: none;
border: 10px solid #404b69;
font-size: 5rem;
line-height: 1;
font-weight: 900;
color: #da0463;
text-shadow: 3px 0 #dbedf3;
border-radius: 15px;
display: inline-block;
width: 110px;
height: 110px;
text-align: center;
margin: 5px;
background-color: white;
}
<h1 id="title">Color Palette</h1>
<div class="set">
<button id="a" class="a palette">a</button>
<button id="b" class="b palette">b</button>
<button id="c" class="c palette">c</button>
<button id="d" class="d palette">d</button>
</div>
<div>
<button id="generate">generate</button>
</div>
如果我们将颜色代码添加到函数中,我们可以调用它setColors
,我们可以在页面渲染上调用该函数,当按下按钮时,如下所示:
function setColors() {
// Color code
}
// Run on start
setColors()
// Run on button click
document.getElementById("generate").addEventListener("click", setColors);
Snippet:
function setColors() {
document.querySelectorAll(".palette").forEach(function (btn) {
var n = Math.random();
n = n * 256;
n = Math.floor(n);
var a = Math.random();
a = a * 256;
a = Math.floor(a);
var b = Math.random();
b = b * 256;
b = Math.floor(b);
var color = "rgb(" + n + "," + a + "," + b + ")";
btn.style.backgroundColor = color;
});
}
// Run on start
setColors()
// Run on button click
document.getElementById("generate").addEventListener("click", setColors);
body {
text-align: center;
background-color: black;
}
.palette {
outline: none;
border: 10px solid #404b69;
font-size: 5rem;
line-height: 2;
font-weight: 900;
color: #da0463;
text-shadow: 3px 0 #dbedf3;
border-radius: 15px;
display: inline-block;
width: 150px;
height: 150px;
text-align: center;
margin: 10px;
background-color: white;
}
<h1 id="title">Color Palette</h1>
<div class="set">
<button id="a" class="a palette">a</button>
<button id="b" class="b palette">b</button>
<button id="c" class="c palette">c</button>
<button id="d" class="d palette">d</button>
</div>
<div>
<button id="generate">generate</button>
</div>
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)