javascript计算器输入背景

时间:2015-11-29 22:11:45

标签: javascript calculator

嗨,出于教育目的,我试图用我的计算器做一些事情,我试图让显示器根据结果改变颜色,这是我最接近的,但它只是显示红色没有无论结果如何,我还需要添加什么?

 <script>
 function checkNum() {
 var x = document.kalk.disp.value; 
 if (x.match(/[a-zA-Z]+/)) { 
     kalk.disp.value=("Endast siffror!"); 
    kalk.disp.style.background = "red"; 
 }   else {
    kalk.disp.value = eval(x);
   (eval.value===0)
    kalk.disp.style.background = "green";
   (eval.value>=1)
    kalk.disp.style.background = "blue";
  (eval.value<=-1)
    kalk.disp.style.background = "red";
}
}
</script>

这是html

 <form name="kalk"> 
 <input type="text" name="disp" >
 <br>
 <input type="button" value="7" OnClick="kalk.disp.value+='7'">
 <input type="button" value="8" OnClick="kalk.disp.value+='8'">
 <input type="button" value="9" OnClick="kalk.disp.value+='9'">
 <input type="button" value="*" OnClick="kalk.disp.value+='*'">
 <br>
 <input type="button" value="4" OnClick="kalk.disp.value+='4'">
 <input type="button" value="5" OnClick="kalk.disp.value+='5'">
 <input type="button" value="6" OnClick="kalk.disp.value+='6'">
 <input type="button" value="-" OnClick="kalk.disp.value+='-'">
 <br>
 <input type="button" value="1" OnClick="kalk.disp.value+='1'">
 <input type="button" value="2" OnClick="kalk.disp.value+='2'">
 <input type="button" value="3" OnClick="kalk.disp.value+='3'">
 <input type="button" value="+" OnClick="kalk.disp.value+='+'">
 <br>
 <input type="button" value="C" OnClick="kalk.disp.value=''">
 <input type="button" value="0" OnClick="kalk.disp.value+='0'">
 <input type="button" value="." OnClick="kalk.disp.value+='.'">
 <input type="button" value="=" OnClick="checkNum()" >
 </form>

基本上我已经添加了

 (eval.value===0)
 kalk.disp.style.background = "green";
 (eval.value>=1)
 kalk.disp.style.background = "blue";
 (eval.value<=-1)
  kalk.disp.style.background = "red";

2 个答案:

答案 0 :(得分:0)

您使用的是eval错误。

你需要一些if语句或类似的东西:

function checkNum() {
    var x = document.kalk.disp.value;
    if (x.match(/[a-zA-Z]+/)) {
        kalk.disp.value = ("Endast siffror!");
        kalk.disp.style.background = "red";
    } else {
        var result = eval(x);

        kalk.disp.value = result;
        if (result > 0) {
            kalk.disp.style.background = "blue";
        } else if (result === 0) {
            kalk.disp.style.background = "green";
        } else {
            kalk.disp.style.background = "red";
        }

    }
}

fiddle

答案 1 :(得分:0)

function checkNum() {
var x = document.kalk.disp.value;
if (x.match(/[a-zA-Z]+/)) {
    kalk.disp.value = ("Endast siffror!");
    kalk.disp.style.background = "red";
} else {
    var result = eval(x);

    kalk.disp.value = result;
    if (result > 0) {
        kalk.disp.style.background = "blue";
    } else if (result === 0) {
        kalk.disp.style.background = "green";
    } else {
        kalk.disp.style.background = "red";
    }

}