简体   繁体   English

HTML中文本的条件着色

[英]Conditional coloring of text in HTML

I want to change the color of some text on my website depending on whether input from a php script is X or Y, is this possible without doing Javascript, which I would like to avoid. 我想根据自己的php脚本输入是X还是Y来更改网站上某些文本的颜色,是否可以不用Javascript来做到这一点,我想避免这种情况。

I have read: Conditional Formatting in HTML Tags but I am wondering if there has been any changes/updates that makes this possible now. 我读过: HTML标记中的条件格式,但是我想知道是否有任何更改/更新现在使之成为可能。

No JS: 没有JS:

I think the following would work: 我认为以下方法会起作用:

/* Define different colors to the input class */
.X{
  color: red;
}
.Y{
  color: blue;
}

/* set the input class as the input value */   
<label class="<?=value?>" name="<?=value?>"> Some Text </label>

If you are outputting html on the same page you can try something like this: 如果您在同一页面上输出html,则可以尝试如下操作:

<?php
$colour = 'green';

if(rand(0, 99) >= 50) {
    $colour = 'red';
}
?>
<div style="color:<?=$colour?>;">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod 
    tempor incididunt ut labore et dolore magna aliqua.
</div>

The rand is just to mimic the different values in a test scenario. 兰特仅用于模拟测试方案中的不同值。

Yes, you just set inject the right tags from PHP. 是的,您只需设置从PHP注入正确的标签即可。 You can do this by generating the CSS from PHP, but since its more common to write dynamic HTML with PHP and use static CSS, an inline style is probably the most appropriate approach: 您可以通过从PHP生成CSS来做到这一点,但是由于使用PHP编写动态HTML并使用静态CSS更为常见,因此内联样式可能是最合适的方法:

$your_colour=($your_condition) ? "green" : "red";
print "<span style='color:$your_colour'>"; 
...
print "</span>"

If you are applying this in several places, then you might consider using a inline css class. 如果要在多个地方应用此方法,则可以考虑使用内联css类。

<style>
 .false_condition {COLOR:red}
 .true_condition{COLOR:green}
</style>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM