繁体   English   中英

如何改变 <li> 要么 <tr> 颜色相继

[英]How to change <li> or <tr> color after one another

我想改变li或tr之后的颜色。

注意: - 我想在while循环中调用它,所以静态类将无法解决

我想要输出lke: -

<li>line1</li> //white background
<li>line2</li> //red background
<li>line3</li> //white background
<li>line4</li> //red background

或者如果可能的话:

<tr>
<td>line1</td>  //white background
</tr>
<tr>
<td>line2</td>  //red background
</tr>
<tr>
<td>line3</td>  //white background
</tr>
<tr>
<td>line4</td>  //red background
</tr>

我正在尝试的是: -

<?php
$fields = CFS()->get('gallery');
foreach ($fields as $field) { <?
<table>
<tr><td><?php echo $field['slide_title']; ?></td></tr>
<tr><td><?php echo $field['upload']; ?></td></tr>
</table>
<?php }  ?>

你可以通过CSS实现这个:nth-of-type奇数和偶数选择器。

JSFiddle - DEMO

li:nth-of-type(odd) {
    color:red;
}
li:nth-of-type(even) {
    color:blue;
}

对于td的选择器:

JSFiddle - DEMO

table tr:nth-of-type(odd) {
    color:red;
}
table tr:nth-of-type(even) {
    color:blue;
}

您也可以使用CSS :nth-child选择器,如下所示:

JSFiddle - DEMO

table tr:nth-child(2n+1) {
    color:red;
}
table tr:nth-child(2n) {
    color:blue;
}

注意: tr:nth-child(2n) - 表示HTML表的偶数行。

tr:nth-child(2n+1) - 表示HTML表的奇数行。

试试这个PHP代码,

$i = 1;
$result = "";
while(ur-condition)
{
  if($i%2 == 0)
    $result .= "<li style='background-color: red'>line$i</li>";
  else
   $result .= "<li style='background-color: white'>line$i</li>";
  $i++;
}

echo $result;

HTML

<ul>
    <li>One</li>
    <li>Two</li>
    <li>Three</li>
    <li>Four</li>
    <li>Five</li>
</ul>    

CSS

*{margin:0; padding:0; font-family:Arial; font-size:12px; color:#333;}
ul, li{list-style:none;}
ul{margin:10px;}
li:nth-child(odd){background-color:blue;}
li:nth-child(even){background-color:red;}
li{line-height:22px; padding:5px; color:#fff;}

小提琴

你可以使用jquery,它也适用于旧版本的ie

http://jsfiddle.net/victor_007/96d0k2zo/

$( "tr:odd , ul li:odd" ).css( "background-color", "#bbbbff" );

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM