[英]Adding PHP alternate table row colours to existing HTML table
我有一个已经用PHP编写的表,它可以回显从数据库中调用的数据,如下所示:
<TABLE cellSpacing=1 cellPadding=2 align=center bgColor=#aaaaaa border=0 width="100%" class="logintbl">
<TR>
<TD bgColor=whitesmoke colSpan=0><B>Pages</B></td>
</tr>
<tr>
<td>
<table align="center" cellSpacing=0 cellPadding=2 border="0" width="100%">
<tr>
<td align="center" valign="bottom"> <font color="#4d71a1"><b>Page Name</b></font> </td>
</tr>
<?php while ($row = mssql_fetch_array($result)) { ?>
<tr bgcolor="#eeeeee">
<td align="center"><?php echo $row["PageURL"]; ?></td>
<td align="center">
<a href="PageUpdate.php?id=<?php echo $row["PageID"]; ?>"><img src="images/0013-pen.gif" width="16" height="16" alt="" border="0"></a>
</td>
</tr>
<?php } ?>
<tr><td colspan="7"> </td></tr>
<tr>
<td colspan="7" align="center">
</td>
</tr>
</table>
</td>
</tr>
</table>
我一直在尝试使用一小段PHP替换行的颜色,并在进行一些研究后实现了这一点:
<tr bgcolor="<?php echo ($clrCounter++ % 2 == 0 ? '#000000' : '#ffffff'); ?>">
它似乎无法正常工作,所以我觉得我在某个地方出错了,我知道可以实现的实现方法更长。 我只是希望简单一些。 我是否在努力尝试以这种方式实施?
我将其集成如下:
<TABLE cellSpacing=1 cellPadding=2 align=center bgColor=#aaaaaa border=0 width="100%" class="logintbl">
<TR>
<td bgColor=whitesmoke colSpan=0><B>Pages</B></td>
</tr>
<tr>
<td>
<table align="center" cellSpacing=0 cellPadding=2 border="0" width="100%">
<tr bgcolor="#3A7525">
<td align="center" valign="bottom"> <font color="#4d71a1"><b>Page Name</b></font> </td>
</tr>
<?php while ($row = mssql_fetch_array($result)) { ?>
<tr bgcolor="<?php echo ($clrCounter++ % 2 == 0 ? '#C2C2C2' : '#ffffff'); ?>">
<td align="center"><?php echo $row["PageURL"]; ?></td>
<td align="center">
<a href="PageUpdate.php?id=<?php echo $row["PageID"]; ?>"><img src="images/0013-pen.gif" width="16" height="16" alt="" border="0"></a>
</td>
</tr>
<?php } ?>
<tr>
<td colspan="7" align="center">
</td>
</tr>
</table>
</td>
</tr>
</table>
这有点奏效,但是由于某种原因,第一个条目是蓝色的? 当我指定白色和灰色时。
使用CSS选择器:nth-of-type( )
。
通过为:nth-of-type(even)
和:nth-of-type(odd)
设置不同的样式,浏览器可以为您完成交替的样式设置,因此您不必担心。
请参阅W3Schools条目。
在遍历数据库返回的结果时,可以使用以下命令:
<?php
// Define row colors
$color1 = "#FFFFFF";
$color2 = "#F4F9FF";
// Set row counter
$row_count = 0;
while ($row = mssql_fetch_array($result)) {
$row_color = ($row_count % 2) ? $color1 : $color2;
?>
<tr bgcolor="<?php echo $row_color; ?>">
<td align="center"><?php echo $row["PageURL"]; ?></td>
<td align="center">
<a href="PageUpdate.php?id=<?php echo $row["PageID"]; ?>"><img src="images/0013-pen.gif" width="16" height="16" alt="" border="0"></a>
</td>
</tr>
<?php
$row_count++;
}
?>
或者,您可以替换bgcolor标记,并为每行分配一个CSS类。
尝试这个:
<tr <?php if($i%2){?>bgcolor="#eeeeee"<?php } else{ ?>bgcolor="red" <?php } $i++; ?>>
感谢Bas van den Heuvel为使用CSS提供的出色答案。 如果像我一样遇到额外的行距,并且想要删除它,请使用以下示例代码。 这将使交替的色线更加紧密。 (我使用浅灰色和白色)
p:nth-of-type(odd)
{
background:#e2e2e2;
margin: 0px;
padding: 0px;
}
p:nth-of-type(even)
{
background:#ffffff;
margin: 0px;
padding: 0px;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.