如何动态改变td的颜色

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

我想动态更改td的颜色,这是我的代码:

<td>
<?php 
    if($status === 'On time'){
        $color = "green";
    }elseif ($status === 'No data') {
        $status = "Address Not Found";
        $color = "red";
    }else{
        $status = "Free Slot";
        $color = "grey";
    }
?>
<?php echo $status; ?>
<?php

}

?>

</td>

我想改变td的颜色取决于我从PHP端收到的状态。

那么如何动态地为td添加颜色?

php html html-table
3个回答
0
投票

试试这个

<?php 
$status = 'On time';
if ($status === 'On time'){
    $color = "green";
} elseif ($status === 'No data') {
    $status = "Address Not Found";
    $color = "red";
} else {
    $status = "Free Slot";
    $color = "grey";
}
?>
<table>
    <tr>
        <td style="background-color: <?php echo $color; ?>"><?php echo $status; ?></td>
    </tr>
</table>

0
投票

另一种可以使用css管理它的方法,没有任何PHP条件。

<table>
    <tr>
        <td class="status_<?php echo $status; ?>"><?php echo $status; ?></td>
    </tr>
</table>


<style>
td.status_On.time{
    color: green;
}
td.status_No.data{
    color: red;
}
td.status_Free.Slot{
    color: grey;
}

</style>

0
投票

您应该在输出之前将颜色设置为某个变量,然后在“td”标记内将其打印为bgcolor或css(style =“background-color:#...”)属性。简单方案:

<?php
    $color = "#000000"; //set color before output
?>
...
<td bgcolor="<?=$color?>"></td> <!--short php variable output inside html code -->

结果:

<td bgcolor="#000000"></td>
© www.soinside.com 2019 - 2024. All rights reserved.