【问题标题】:Adding background color to element within php if-statement在 php if 语句中为元素添加背景颜色
【发布时间】:2016-11-15 19:44:31
【问题描述】:

我有以下代码,我想在我的 if 语句中添加一个元素,但我不确定如何处理这个问题。我要做的是为它的 else 部分添加背景颜色。在此:

else {
        $status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
}

所以如果$status不为0,我想为goal-box-right类设置背景色。

有没有我可以像这样通过 php 操作 CSS?

foreach ($rows as $row) {
            $status = $row['status'];
            if ($status == 0) {
                $status_img = '<img src="../icons/collection/x-sign.png" alt="Goal Not Complete">';
            }
            else {
                $status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
            }
            $goal_date = $row['date'];
            $fixed_goal_date = fixDate($goal_date);
            $html = "";
            $html .= '<div class="goal-box" id="comment-'.$row['id'].'">';
            $html .= '<div class="goal-box-left">'; //added
            $html .= '<div class="goal-post-status">'.$status_img. '</div>';
            $html .= '</div>'; //added
            $html .= '<div class="goal-box-right">'; //added
            $html .= '<div class="goal-post-title">'.$row['title']. '</div>';
            $html .= '<div class="goal-post-date">'.$fixed_goal_date. '</div>';
            $html .= '<div class="goal-post-description">'.$row['description']. '</div>';
            $html .= '</div>'; //added
            $html .= '</div>';

【问题讨论】:

  • 问题出在哪里?
  • 为什么不将背景色设置为内联样式?
  • 问题是我不知道如何通过我的if语句将背景颜色设置为不同的颜色。
  • 您使用一个额外的 css 类来轮询每个特定的背景颜色。这样您就可以轻松地通过 php 进行切换,您只需为元素分配不同的类。这样可以防止您必须使用动态 css,这会使 css 不可缓存。
  • @arkascha 感谢您的提示。

标签: php html css json if-statement


【解决方案1】:

分离逻辑 - 根据状态添加 CSS 类,然后在样式表中设置颜色。

$class = $status != 0 ? 'status-nonzero' : '';

$html .= '<div class="goal-box-right ' . $class . '">';

CSS:

.goal-box-right.status-nonzero { background-color: #foo }

优点是将样式逻辑保留在其所属的 CSS 中,并远离生成 HTML 的代码。

【讨论】:

  • 感谢这个方法。我用过这个,效果很好。再次感谢。
【解决方案2】:

那么问题出在哪里:

$style = '';
if ($status == 0) {
    $style = ' style="your-style:here"';
    $status_img = '<img src="../icons/collection/x-sign.png" alt="Goal Not Complete">';
}
else {
    $status_img = '<img src="../icons/collection/checkmark.png" alt="Goal Complete">';
}

// ...
$html .= '<div class="goal-box-right"' . $style . '>'; //added

【讨论】:

  • 效果很好。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-12-12
相关资源
最近更新 更多