如何设置一个常规元素的背景色,然后通过一个事件(onclick)设置一个特定元素(同一种)的背景色?

时间:2018-12-03 03:52:24

标签: javascript html css

所以我有这个UltraTicTacToe游戏,我正在使用HTML / CSS / JS进行编码。它由表中的表内的表组成。当您单击X或O时,我希望您进入下一个TicTacToe表格/游戏以突出显示。我想将突出显示的表格/游戏重新设置为白色,然后突出显示另一个表格/游戏。我目前正在尝试通过使用以下功能来实现此功能:将所有表格的背景颜色设置为白色,然后将特定表格的背景颜色设置为黄色,但是它拒绝为我工作...有什么想法吗?

function tableReset() {
  document.getElementByClassName('tabler').style.backgroundColor = 'white';
}

function hide1() {
  document.getElementById('o1').style.display = 'none';
}

function reSize1() {
  document.getElementById('x1').style.width = '100%';
}

function nextMove1() {
  document.getElementById('st1').style.backgroundColor = 'yellow';
}
<table class="tabler" id="st1">
  <tr class="topmid">
    <td>
      <button type="button" class="x" id="x1" onclick="hide1(); reSize1(); tableReset(); nextMove1();">X</button>
      <button type="button" class="o" id="o1" onclick="hide2(); reSize2(); tableReset(); nextMove1();">O</button>
    </td>

Here is a pic of the game look - UltraTICTACTOE

2 个答案:

答案 0 :(得分:1)

getElementsByClassName返回一个HTMLCollection。您可以使用document.getElementsByClassName('tabler')[0]获取其第一个元素,也可以使用getElementById

function tableReset() {
  //document.getElementsByClassName('tabler')[0].style.backgroundColor = 'white';
  //or
  document.getElementById('st1').style.backgroundColor = 'white';
}

function hide1() {
  document.getElementById('x1').style.display = 'none';
}
function hide2() {
  document.getElementById('o1').style.display = 'none';
}
function reSize1() {
  document.getElementById('x1').style.width = '100%';
}
function reSize2() {
  document.getElementById('o1').style.width = '100%';
}

function nextMove1() {
  document.getElementById('st1').style.backgroundColor = 'yellow';
}
<table class="tabler" id="st1">
  <tr class="topmid">
    <td>
      <button type="button" class="x" id="x1" onclick="hide1(); reSize1(); tableReset(); nextMove1();">X</button>
      <button type="button" class="o" id="o1" onclick="hide2(); reSize2(); tableReset(); nextMove1();">O</button>
    </td>

答案 1 :(得分:0)

如果其他人遇到此问题,这将全部选中!

var myNodelist = document.querySelectorAll("table");
var i;
for (i = 0; i < myNodelist.length; i++) {
    myNodelist[i].style.backgroundColor = "white";
}