猿问

显示三元运算符的颜色

如果我的三元运算符返回为真,我试图显示一种颜色,如果返回为假,则显示另一种颜色。操作员正在工作,但有一件事发生了。双引号内的代码显示而不是实际颜色本身。有人知道怎么修这个东西吗 ?

$msg .= ($row['opened'] == '0') ? "background-color: #DDEDFF;" : "background-color: #000000;";

https://img3.mukewang.com/6504264b00014de202470071.jpg

https://img2.mukewang.com/650426510001178002410071.jpg

编辑!!!$msg- 这是我的变量唯一出现的时间

public function getLatestMessage ($userLoggedIn, $user2) {


    $query = $this->con->prepare('SELECT body, user_to, opened, date FROM messages WHERE 

        user_to = ? AND user_from = ? OR user_to = ? AND user_from = ? ORDER BY id DESC LIMIT 1'); 

    $query->bind_param("ssss", $userLoggedIn, $user2, $user2, $userLoggedIn);

    $query->execute();

    $query_result = $query->get_result();


    $msg = ""; //to hold the message data


    if ($row = $query_result->fetch_assoc()) { //don't need a while here because we've limited the query to one record


        //Timeframe

        $date_time_now = date("Y-m-d H:i:s");

        $start_date = new DateTime($row['date']); //Time of post

        $end_date = new DateTime($date_time_now); //Current time

        $interval = $start_date->diff($end_date); //Difference between dates 

        if($interval->y >= 1) {

            if($interval->y == 1)

                $time_message = $interval->y . "yr"; //1 year ago

            else 

                $time_message = $interval->y . "yrs"; //1+ year ago

        }

        else if ($interval-> m >= 1) {

            if($interval->d == 0) {

                $days = " ago";

            }

            else if($interval->d == 1) {

                $days = $interval->d . "d";

            }

            else {

                $days = $interval->d . "d";

            }


            if($interval->m == 1) {

                $time_message = $interval->m . "month";

            }

            else {

                $time_message = $interval->m . "months";

            }


        }



喵喵时光机
浏览 92回答 1
1回答

繁星coding

您的代码完全按照您的指示进行操作:输出一个字符串,其中显示“背景颜色:...”。浏览器如何知道您想要使用该颜色设置文本样式,而不是将这些单词呈现给用户?您需要为浏览器指定这是您提供的样式。代替&nbsp; &nbsp; &nbsp; &nbsp; $msg .= ($row['opened'] == '0') ? "background-color: #DDEDFF;" : "background-color: #000000;";尝试类似的东西:&nbsp;$color = $row['opened'] == '0' ? "#DDEDFF" : "#000000";&nbsp;$msg .= "<span style='background-color:$color'>THE TEXT YOU WANT TO COLORIZE</span>";完整示例<?phpfunction getLatestMessage($opened) {&nbsp; &nbsp; $color = $opened ? "#DDEDFF" : "#000000";&nbsp; &nbsp; $msg = "<span style='background-color:$color'>THE TEXT YOU WANT TO COLORIZE</span>";&nbsp; &nbsp; return $msg;}echo getLatestMessage(true);echo getLatestMessage(false);?>
随时随地看视频慕课网APP
我要回答