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

问题描述 投票:-3回答:2

我有一个重复的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,欢迎任何事情。提前致谢。

javascript css
2个回答
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>

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>
热门问题
推荐问题
最新问题