【发布时间】:2019-01-04 14:22:36
【问题描述】:
我有一个简单的程序,您可以在其中选择一种颜色并用它填充一个框。我有一个 4x4 的框(div)网格,我想检查所有 div(框)的 backgroundColor 是否有一个值,以便当所有框都填充有颜色时,网格重置并且所有框再次为空白.
但是,我在实现这一点时遇到了一些问题。我的第一个想法是检查数组中的每个 div(我使用 querySelectorAll)是否具有 backgroundColor 'red' 或 'blue'。我试图将数组项的 backgroundColor 存储到一个变量中,但是当我控制台记录它时它不会返回字符串。
我还尝试了 Array 上的 every() 方法,但似乎没有用。
所以我的问题是,如何获取节点列表中元素的背景颜色并检查该元素是否具有背景颜色。
这是我的 JavaScript 代码:
var redColor = document.getElementById('red');
var blueColor = document.getElementById('blue');
var box = document.querySelectorAll('.box');
var colorPick = document.getElementById('color picker');
let currentColor = [];
Array.from(box);
console.log(box);
loadEventListeners();
function loadEventListeners(){
redColor.addEventListener('click', pickRed);
blueColor.addEventListener('click', pickBlue);
for (i = 0; i < box.length; i++){
box[i].addEventListener('click', addColor);
}
};
function pickRed(e){
currentColor.push('red');
var textRed = document.createTextNode("You have selected red");
colorPick.appendChild(textRed);
console.log(currentColor);
}
function pickBlue(e){
currentColor.push('blue')
console.log(currentColor);
}
function addColor(e){
if (currentColor.slice(-1)[0] === 'blue'){
e.currentTarget.style.backgroundColor = 'blue';
} else { e.currentTarget.style.backgroundColor = 'red';
}
}
这是我正在使用的 HTML:
<!DOCTYPE html>
<html>
<head>
<style>
.container{
grid-template-columns: repeat(5, 1fr);
grid-column-gap: 200px;
display: grid;
align-items: auto;
width: 50%;
margin: auto;
}
.game-grid{
display: grid;
grid-template-columns: repeat(4, 100px);
margin: 0;
}
#color-picker{
display: grid;
grid-template-rows: 100px 50px 50px;
}
.box{
width: 100px;
height: 100px;
border: solid 2px;
}
#red{
background-color: red;
width: 50px;
height: 50px;
}
#blue {
background-color: blue;
width: 50px;
height: 50px;
}
</style>
</head>
<body>
<div class="container">
<div class="game-grid">
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
<div class="box"></div>
</div>
<div id="color picker">
<h2>Pick a color!</h2>
<div id="red"></div>
<div id="blue"></div>
<div id="green"></div>
</div>
</div>
</body>
</html>
感谢您的帮助!
【问题讨论】:
-
Array.from(box);不会像您认为的那样做。它返回一个新数组,您没有存储它。它不会改变盒子。
标签: javascript html css