我有一个div,我想根据div中的int值更改颜色,但是由于某些原因,它不会根据我编写的if else语句更改颜色。而是没有颜色出现。这是为什么?

<div id="test">66</div>


JAVASCRIPT

var testDiv = document.getElementById("test");

if (testDiv<50) {
    testDiv.style.backgroundColor = '#900000';
} else if (testDiv > 49 && testDiv < 75) {
    testDiv.style.backgroundColor = '#FF9933';
} else if (testDiv > 74) {
    testDiv.style.backgroundColor = '#00CC00';
}

最佳答案

您正在尝试检查元素的innerHTML,但要与元素本身进行比较。尝试:

var testDiv = document.getElementById("test");
var value = parseInt(testDiv.innerHTML);
if(value<50){
    testDiv.style.backgroundColor = '#900000';
}
else if(value>49 && value <75){
    testDiv.style.backgroundColor = '#FF9933';
}
else if(value>74){
    testDiv.style.backgroundColor = '#00CC00';
}

关于javascript - JavaScript,如果其他问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28355558/

10-12 07:35