Divs上的背景颜色交替



我需要将Divs的行分为颜色。

在尝试在我们的后端/前端实现它之前,我正在尝试在常规浏览器中使用此功能。所以这是我拥有的测试代码。我一生无法找到为什么这不起作用。我已经尝试使用身体而不是在脚本标签中进行on载,但我尝试链接到外部JS。我认为示例代码这将是最简单的方法。

<!doctype html>
<html lang="en">
<head>
  <meta charset="utf-8">
  <title></title>
  <meta name="description" content="HTML5">
  <meta name="author" content="Site">
  <style>
    .testclass {
      width: 100%;
      height: 10px;
      background-color: #fdc345;
    }
  </style>
</head>
<body>
  <div class="testclass"></div>
  <div class="testclass"></div>
  <div class="testclass"></div>
  <div class="testclass"></div>
  <script>
    function isEven(value) {
      if (value % 2 == 0) {
        return true;
      } else {
        return false;
      }
    }
    function setColors() {
      var userList = document.getElementsByClassName("testclass");
      var i;
      for (i = 0 i < userList.length; i++) {
        if (isEven(i) == true) {
          userList[i].style["background-color"] = "red";
          /* I also tried document.getElementsByClassName("testclass")[i].style.backgroundColor = "red" */
        } else {
          userList[i].style["background-color"] = "blue";
        }
      }
    }
    window.onload = setColors;
  </script>
</body>
</html>

我在这里想念什么?

正如控制台中的错误所说,您错过了前面的;。添加它,并且起作用。

注意我还简化了您的isEven()功能。正如@nathan所述,您还可以通过删除此功能并在if Statment上进行测试。

function isEven(value) {
    return (value % 2 == 0);
}
function setColors() {
    var userList = document.getElementsByClassName("testclass");
    var i;
    for (i = 0; i < userList.length; i++) { // <-- /! Here /!
      if (isEven(i)) {
        userList[i].style["background-color"] = "red";
      } else {
        userList[i].style["background-color"] = "blue";
      }
    }
}
window.onload = setColors;
.testclass {
  width: 100%;
  height: 10px;
  background-color: #fdc345;
}
<div class="testclass"></div>
<div class="testclass"></div>
<div class="testclass"></div>
<div class="testclass"></div>

,为什么不只是停止让事情复杂化呢?当应付CSS和JavaScript时,请使用CSS。

    <style>
.testclass {
      width: 100%;
      height: 10px;
      background-color: #fdc345;
    }
    .even{
background-color:red !important;
}
    .odd{
background-color:blue !important;
}
    </style>
    /... rest of code .../
    <div class="testclass even"></div>
    <div class="testclass odd"></div>
    <div class="testclass even"></div>
    <div class="testclass odd"></div>

SyntaxError:缺少;循环初始化器(代码中的第36行)。

所以,使用:

for (i=0; i<userList.length; i++) {
//...
}

- 与JavaScript一起工作时,请在浏览器的控制台或JS错误(F12)中检查。

与JavaScript一起使用,而CSS pseudo类:nth-child进行营救...

https://developer.mozilla.org/en/docs/web/css/:nth-child

.testclass {
  height:1em;
  margin: 1em;
  background: red;
}
.testclass:nth-child(2n) {
  background: green;
}
<div class="container">
  <div class="testclass"></div>
  <div class="testclass"></div>
  <div class="testclass"></div>
  <div class="testclass"></div>
</div>

最新更新