dov11020 2013-07-29 13:03
浏览 30
已采纳

基于条件语句改变文本背景的颜色

I would like to be able to write a script that changes the background text color based on a conditional statement. The statement is based on matching two numbers. If the numbers match, then the background text color should be green. If the numbers do not match, then the background color should be red. I currently have the following script:

<script>
    function myFunction(tBox)
    {
        var sum=0;
        var elts = document.getElementsByTagName('input');
        for (var i=0; i<elts.length; i++)
        {
           var elt=elts[i];
           if ( elt.id && elt.id.indexOf('hous')===0) sum += Number(elt.value);
        }
        document.getElementById('sum').innerText = sum;
    }
</script>

This script simply sums together all of the text inputs with the prefix 'hous' and the number that concerns this question is the actual outputted sum of this function, which is outputted with:

<p id="sum"></p>

The sum output is what needs to be highlighted either red or green based on the conditional statement. The number I would like to compare this sum to is a result of this statement:

<?php echo ($_POST["qty"])*$qtyHous; ?>

Where "qty" is a text input and $qtyHous is a scaling factor. So, my question is:

How do I write the javascript that will compare these two numbers in a way that makes the text background color behind the sum turn green (the two numbers are equal) or red (the two numbers are not equal)?

  • 写回答

1条回答 默认 最新

  • douxiangbiao1899 2013-07-29 13:13
    关注

    you could access to the background color with the style.backgroundColor component like this

    if(sum != x)
       document.getElementById('sum').style.backgroundColor = 'red';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 求差集那个函数有问题,有无佬可以解决
  • ¥15 【提问】基于Invest的水源涵养
  • ¥20 微信网友居然可以通过vx号找到我绑的手机号
  • ¥15 寻一个支付宝扫码远程授权登录的软件助手app
  • ¥15 解riccati方程组
  • ¥15 display:none;样式在嵌套结构中的已设置了display样式的元素上不起作用?
  • ¥15 使用rabbitMQ 消息队列作为url源进行多线程爬取时,总有几个url没有处理的问题。
  • ¥15 Ubuntu在安装序列比对软件STAR时出现报错如何解决
  • ¥50 树莓派安卓APK系统签名
  • ¥65 汇编语言除法溢出问题