<script type="text/javascript">
function display(){
var resultBox = document.getElementById("resultbox");
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var result = input1.value * input2.value;
resultBox.value = result;
}
</script>
我正在使用这个,但我希望如果答案是1-3,结果显示为绿色,如果答案是4-9,结果显示为黄色,如果答案是10-19,结果显示为橙色,如果答案是红色,结果显示为20>上面的代码工作,但当我添加了改变颜色的功能,它不会改变颜色
<script type="text/javascript">
function display(){
var resultBox = document.getElementById("resultbox");
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var result = input1.value * input2.value;
resultBox.value = result;
}
if (resultBox <=3) {
resultBox = document.getElementById("p2").style.color = "green";
} else if (resultBox<=9) {
resultBox = document.getElementById("p2").style.color = "yellow";
}
else if (resultBox <=19) {
resultBox = document.getElementById("p2").style.color = "orange";
}
else {
resultBox = document.getElementById("p2").style.color = "red";
}
</script>
像这样的行
resultBox = document.getElementById("p2").style.color = "orange";
你已经结合了p2
元素和设置它的颜色,但这是不正确的。结果将是您的颜色改变,但resultBox
在其中具有orange
的值。
如果你想这样做,使用两行:
resultBox = document.getElementById("p2");
resultBox.style.color = "orange";
或括号强制顺序(不推荐):
(resultBox = document.getElementById("p2")).style.color = "orange";
更重要的是,您的代码只执行一次——只在页面第一次加载时执行。试着将代码放在display()
函数内更改结果框文本颜色,以便每次调用display()
时都运行:
(在这段代码中我还整理了一下缩进和代码)
<script type="text/javascript">
function display(){
var resultBox = document.getElementById("resultbox");
var input1 = document.getElementById("input1");
var input2 = document.getElementById("input2");
var result = input1.value * input2.value;
resultBox.value = result;
if (resultBox <=3) {
resultBox.style.color = "green";
} else if (resultBox<=9) {
resultBox.style.color = "yellow";
} else if (resultBox <=19) {
resultBox.style.color = "orange";
} else {
resultBox.style.color = "red";
}
}
</script>