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';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?