[英]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.