gpt4 book ai didi

javascript计算器输入背景

转载 作者:行者123 更新时间:2023-11-28 06:39:17 27 4
gpt4 key购买 nike

嗨,出于教育目的,我尝试用我的计算器做一些事情,我尝试让显示屏根据结果改变颜色,这是我最接近的,但它只是显示红色不不管结果如何,我还需要补充什么吗?

 <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";

最佳答案

您使用的 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

关于javascript计算器输入背景,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33988761/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com