为IF ELSE结果添加颜色格式

时间:2016-02-20 01:13:34

标签: javascript html

我有一个非常基本的if else代码,返回“CORRECT”或“INCORRECT”

如何格式化此文本 “正确”出现在GREEN& “INCORRECT”显示为RED

???

<html>

<script language="javascript">
function QA1()
{
    var ANSWER = document.getElementById("ANSWER").value;
    var RESULT;
    if (ANSWER == '2') {
    RESULT = "CORRECT";
} else {
    RESULT = "INCORRECT";
} 
document.getElementById("RESULT1").innerHTML = RESULT;
}
</script>


<body>

<form method="post">
    <p><input type="text" length="3" id="ANSWER">&nbsp;&nbsp;
<input type="button" value="Enter" onclick="QA1()"></p>
</form>
<p id="RESULT1"></p>

</body>
</html>

2 个答案:

答案 0 :(得分:1)

使用style.color属性修改元素的颜色。

    function QA1()
    {
        var ANSWER = document.getElementById("ANSWER").value;
        var resultCorrect = ANSWER === '2' ? true : false;
        var result1 = document.getElementById("RESULT1");
        var color;
        var resultText;
        if(resultCorrect)
        {
           color = 'green';
           resultText = 'CORRECT';
        }
        else
        {
           color = 'red';
           resultText = 'INCORRECT';
        }

        result1.style.color = color;
        result1.innerHTML = resultText;
    }

答案 1 :(得分:0)

来自W3Schools documentation

  

要更改HTML元素的样式,请使用以下语法:

document.getElementById(id).style.property=new style 
     

以下示例更改<p>元素的样式:

<html>
<body>

<p id="p2">Hello World!</p>

<script>
document.getElementById("p2").style.color = "blue";
</script>

<p>The paragraph above was changed by a script.</p>

</body>
</html>

所以你可以这样做:

var element = document.getElementById("RESULT1");
element.innerHTML = RESULT;
element.style.color = RESULT === 'CORRECT' ? 'green' : 'red';