在偶数/奇数日期更改div的背景颜色

时间:2017-12-30 09:50:38

标签: javascript css

我有一个重复的div行列表作为表,在第一列中有一些日期,如下例所示:

<div>
  <div>20 Dic</div><div>Anything</div>
  <div>20 Dic</div><div>Anything</div>
  <div>21 Dic</div><div>Anything</div>
  <div>22 Dic</div><div>Anything</div>
  <div>22 Dic</div><div>Anything</div>
  <div>22 Dic</div><div>Anything</div>
  <div>23 Dic</div><div>Anything</div>
  <div>24 Dic</div><div>Anything</div>
  <div>24 Dic</div><div>Anything</div>
  <div>25 Dic</div><div>Anything</div>
  <div>26 Dic</div><div>Anything</div>
</div>

我需要用奇怪的一天用背景颜色来格式化任何一行,用另一个用偶数天来格式化,例如:所有div为20,22,24,26,灰色;和21,23,25白色(日期输出来自PHP格式)。请注意,并非所有日期都必须是一行,行数可能会有所不同。

当然,CSS或Javascript,欢迎任何事情。提前谢谢。

2 个答案:

答案 0 :(得分:3)

// get all immediate child divs
var divs = document.querySelectorAll('div > div');

// loop through them
[].forEach.call(divs, function(div) {
  var num = parseInt(div.innerHTML);

  // if it's an odd number, gray the background of that div
  if (!isNaN(num) && num % 2 === 1) {
    div.style.backgroundColor = '#ccc';
  }
});
<div>
  <div>20 Dic</div><div>Anything</div>
  <div>20 Dic</div><div>Anything</div>
  <div>21 Dic</div><div>Anything</div>
  <div>22 Dic</div><div>Anything</div>
  <div>22 Dic</div><div>Anything</div>
  <div>22 Dic</div><div>Anything</div>
  <div>23 Dic</div><div>Anything</div>
  <div>24 Dic</div><div>Anything</div>
  <div>24 Dic</div><div>Anything</div>
  <div>25 Dic</div><div>Anything</div>
  <div>26 Dic</div><div>Anything</div>
</div>

答案 1 :(得分:0)

div.main{
  background:#FF0;
}
div:not(.main):nth-child(2n+1) {background: #CCC !important}
<div class="main">
  <div>20 Dic</div><div>Anything</div>
  <div>20 Dic</div><div>Anything</div>
  <div>21 Dic</div><div>Anything</div>
  <div>22 Dic</div><div>Anything</div>
  <div>22 Dic</div><div>Anything</div>
  <div>22 Dic</div><div>Anything</div>
  <div>23 Dic</div><div>Anything</div>
  <div>24 Dic</div><div>Anything</div>
  <div>24 Dic</div><div>Anything</div>
  <div>25 Dic</div><div>Anything</div>
  <div>26 Dic</div><div>Anything</div>
</div>