偶数或奇数时改变表的颜色

时间:2017-12-17 12:56:03

标签: php html css

我有这行代码(php):

<!DOCTYPE html>
<html>
<head>
<title> okay</title>
</head>
<body>
<?php
echo "<table border=2>";
for ($i = 1; $i <= 10; $i++ ) {  
    echo "<tr>";
    echo "<td >".$i."</td>";
    for ( $j = 2; $j <= 10; $j++ ) {
        echo "<td>".$i * $j."</td>";
    }
    echo "</tr>";
}
echo "</table>";
?>
</body>
</html>

我希望偶数的背景颜色变为绿色(白色字体),奇数变为红色(黑色字体)。 我怎么能这样做?

3 个答案:

答案 0 :(得分:1)

使用php的%运算符来确定奇数/偶数行

<!DOCTYPE html>
<html>
<head>
<title> okay</title>
</head>
<body>
<?php
echo "<table border=2 >";
for ($i = 1; $i <= 10; $i++ ) {  
  $style="background:red;color:black";
  if($i%2==0)      
    $style="background:green;color:white";
echo "<tr style=$style>";
echo "<td >".$i."</td>";
for ( $j = 2; $j <= 10; $j++ ) {
echo "<td>".$i * $j."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>

或者简单地通过css:

tr:nth-of-type(odd)
{
    background:red;color:black;
}
tr:nth-of-type(even)
{
    background:green;color:white;
}

修改

如果要在值为奇数/偶数时更改颜色。尝试以下代码:

<!DOCTYPE html>
<html>
<head>
<title> okay</title>
</head>
<body>
<?php
echo "<table border=2 >";
for ($i = 1; $i <= 10; $i++ ) {    
echo "<tr >";
$style="background:red;color:black";
  if($i%2==0)      
    $style="background:green;color:white";
echo "<td style=$style>".$i."</td>";
for ( $j = 2; $j <= 10; $j++ ) {
  $val = ($i * $j);
  $style="background:red;color:black";
  if($val%2==0)      
    $style="background:green;color:white";
  echo "<td style=$style>".$val."</td>";
}
echo "</tr>";
}
echo "</table>";
?>
</body>
</html>

答案 1 :(得分:0)

我添加了如果partto检查奇数甚至是关于你的chioce的打印

<!DOCTYPE html>
<html>
<head>
<title> okay</title>
</head>
<body>
<?php
echo "<table border=2>";
for ($i = 1; $i <= 10; $i++ ) {  
    echo "<tr>";
    echo "<td >".$i."</td>";
    for ( $j = 2; $j <= 10; $j++ ) {
        if(($i*$j)%2==0)
           echo "<td style="color:white;background-color:green">".$i * $j."</td>";
       else
            echo "<td style="color:black;background-color:red">".$i * $j."</td>";
    }
    echo "</tr>";
}
echo "</table>";
?>
</body>
</html>

答案 2 :(得分:0)

试试这个:

 <?php
if ($i % 2 != "0") # An odd row
  $rowColor = "green";
else # An even row
  $rowColor = "orange"; 
?>