【问题标题】:JavaScript checking the background color of a divJavaScript 检查 div 的背景颜色
【发布时间】: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


【解决方案1】:

querySelectorAll 的结果不是一个完整的数组。它更像是一个“类似数组”的对象。但它不支持every(或forEach,或map ...)。

但是您可以使用Array.from 使其成为一个真正的数组。

但是在你的代码中你只做Array.from(box);。但是这段代码什么也不做,因为 box 不会被修改。你要写box = Array.from(box);或者直接使用:

Array.from(box).every(function(div) {
    return div.style.backgroundColor == 'blue' || div.style.backgroundColor == 'red';
});

【讨论】:

  • 好吧,你错过了 OP 使用 Array 的那一行,但是方法错误。
  • 谢谢!这就是问题所在。
【解决方案2】:

您可以使用getComputedStyle 获取元素的背景颜色。要获取节点列表中多个节点的背景颜色,可以使用Array.from 将节点列表转换为真实数组,然后使用Array.prototype.every

示例展示了如何使用getComputedStyle 以及Array.from

const queryAll = (selector, node = document) => Array.from(node.querySelectorAll(selector));

const getComputedBG = node => window.getComputedStyle(node, null).getPropertyValue('background-color');



const $msgNode = document.querySelector('.msg');

const onClick = e => {
  $msgNode.textContent = getComputedBG(e.target);
}

queryAll('.box').forEach(node => {
  node.addEventListener('click', onClick);
});
.list {
  display: grid;
  grid-template-columns: repeat(3, 1fr);
  grid-auto-rows: 200px;
  grid-gap: 10px;
  margin-bottom: 20px;
}

.box {
  background: #000;
}
.box--color1 {
  background: #c00;
}
.box--color2 {
  background: #00c;
}
<div class="list">
  <div class="box box--color1"></div>
  <div class="box box--color1"></div>
  <div class="box box--color2"></div>
  <div class="box box--color1"></div>
  <div class="box box--color2"></div>
  <div class="box box--color2"></div>
</div>
<div class="msg"></div>

【讨论】:

    【解决方案3】:

    querySelectorAll 返回一个 NodeList,它不是一个数组。它没有像mapfilter 这样的所有漂亮的数组方法。但是,您可以通过以下任一方式将其转换为数组:

    let arr = Array.from(document.querySelectorAll('.box'))
    

    let arr = [...document.querySelectorAll('.box')]
    

    一旦你得到你的数组,你就可以让filter 放开它:

    arr.filter(b => {
      let bg = b.style.backgroundColor;
      return bg === 'red' || bg === 'blue';
    });
    

    这将为您提供一个包含所有已设置背景颜色的框的数组。

    【讨论】:

    • 我不知道 filter() - 我可以将其包装在 if 语句中以检查是否所有 div 都已着色,然后调用清除其背景颜色的函数?
    • 好,检查返回的数组不为空,然后在其上调用.each清除每个框。
    【解决方案4】:

    好的,所以你几乎很好,但我认为你没有花太多时间尝试设计行为。对于 querySelector,我不是 100% 最新的,但你也可以使用 getElementByClassName,它会给你一个 HTMLelement 数组。

    首先,对于颜色选择,我不会将元素推送到数组中,而是简单地更新一个字符串变量,我将调用 myCurrentColor

    然后我的 redColor 函数将 myCurrentColor 更改为红色,蓝色也一样。

    最后对于你卡住的部分,我会保留你的 addColor 但它看起来像这样:

    addColor(htmlEl) {
     if(htmlEl.style.backgroundColor != 'blue' || htmlEl.style.backgroundColor != 'red') {
       htmlEl.style.backgroundColor = myCurrentColor;
     } else {
        return;
     }
    }
    

    示例:https://codepen.io/andrea06590/pen/WLzvpE

    【讨论】:

    • 在大多数浏览器中,背景颜色通常不会返回不是颜色的名称。
    • 我从未听说过这个问题。您是否尝试过按照我的建议使用 Javascript?
    猜你喜欢
    • 1970-01-01
    • 2018-05-04
    • 2017-06-21
    • 1970-01-01
    • 1970-01-01
    • 2011-09-05
    • 2012-02-28
    • 1970-01-01
    • 2013-08-20
    相关资源
    最近更新 更多