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

问题描述 投票:0回答:3

我有这行代码(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>

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

php html css
3个回答
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>

0
投票

我添加了部分来检查奇数甚至是您选择的打印件

<!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>

0
投票

试试这个:

 <?php
if ($i % 2 != "0") # An odd row
  $rowColor = "green";
else # An even row
  $rowColor = "orange"; 
?> 
© www.soinside.com 2019 - 2024. All rights reserved.