这是我想做的蚀刻草图项目,我得到了两个主要功能,它们是灰度级(每次通过都变暗)和彩虹,它们在悬停时输出随机颜色
我想接下来添加预设颜色,但是由于某种原因它没有更新。我已经尝试了所有可以考虑的事情,例如将值添加到仅保留当前值的数组中,以设置有效的e.target.style.backgroundColor = className[0];
。
问题是我想使用自己的颜色阴影而不是预定义的CSS颜色名称(我知道我拥有的rgb值与默认值相同,但这是临时的)。
我发现,如果我在updateColor()函数内部为currentColor分配一个值,则它可以工作,但当然会失去所有灵活性。
我已将console.log()放在函数内部,以查看它是否正在接收该值,并且确实是,但是由于某种原因,它根本没有更新。
PS:我为乱码表示歉意
编辑:编辑为最小,完整和可验证的示例
const grid = document.querySelector(".grid");
const clear = document.querySelector("#clear");
clear.addEventListener("click", reset);
function createDivs(){
for(i = 1; i < 16 * 16 + 1; i++){
let createdDivs = document.createElement("div")
grid.appendChild(createdDivs)
createdDivs.setAttribute("class", "grid-element" )
}
grid.style.gridTemplateColumns = `repeat(${16}, 1fr)`
grid.style.gridTemplateRows = `repeat(${16}, 1fr)`
}
createDivs();
function reset(){
let divs = document.querySelectorAll(".grid-element")
divs.forEach(function(div){
div.parentNode.removeChild(div);
});
createDivs();
}
const li = document.querySelectorAll("ul li")
li.forEach(function(e){
e.addEventListener("click", fetchClassName)
})
let className = ["black"]
let oldClassName = ["black"]
let currentColor = "black"
function fetchClassName(e){
className.unshift(e.srcElement.className);
oldClassName = className.pop();
setColor();
}
function setColor(){
let divs = document.querySelectorAll(".grid-element");
switch(className[0]){
case "rainbow":
divs.forEach(function(div){
div.removeEventListener("mouseover", updateColor);
div.addEventListener("mouseover", skittles);
})
break;
case "blue":
currentColor = "rbga(0, 0, 255, 1)"
for (y = 0; y < divs.length; y++){
let div = divs[y];
div.removeEventListener("mouseover", skittles);
div.addEventListener("mouseover", updateColor);
}
break;
}
}
function updateColor(e){
e.target.style.backgroundColor = currentColor //className[0] works but not what I want
console.log(currentColor)
}
function skittles(e){
let r = Math.floor(Math.random() * 256);
let g = Math.floor(Math.random() * 256);
let b = Math.floor(Math.random() * 256);
let rgb = `rgba(${r}, ${g}, ${b}, 0.5)`
e.target.style.backgroundColor = rgb;
}
.grid {
display: grid;
height: 550px;
width: 550px;
}
.grid-element {
grid-area: auto;
border-bottom: 1px solid rgba(0, 0, 0, 0.1);
border-left: 1px solid rgba(0, 0, 0, 0.1);
}
ul li:hover {
cursor: pointer;
}
<div class="container">
<div class="grid"></div>
</div>
<div>
<button type="button" id="clear">Clear Canvas</button>
<ul>
<li class="blue">blue</li>
<li class="rainbow">rainbow</li>
</ul>
</div>
答案 0 :(得分:2)