根据值更改变量的颜色

时间:2021-07-14 11:24:11

标签: javascript html

首先,如果我的问题很简单,我很抱歉,但我才刚刚开始学习和理解。

我有一个开源项目,我正在尝试修改一些小细节,例如更改样式和翻译文本元素。到现在为止还挺好。但是我无法根据输出值更改 html 元素的颜色。在 html 文件中,引用该字段的行是:

<div id="error">0</div>

有一个 Javascript 文件,使项目的辛勤工作。这是我认为应该添加所需内容的功能:

function showScore () {
    if (!numNotes) return;
    const perr = errorCount * opt.pnlerr, ptim = lateNotes * opt.pnltim;
    var score = 100 * (goodNotes - perr - (opt.tmng ? ptim : 0)) / numNotes;
    if (score < 0) score = 0;
    var x = score.toFixed (0) + '%';
    if (opt.scal)
        x = goodNotes +'-'+ perr + (opt.tmng ? '-'+ ptim : '') +'='+ x +' of '+ numNotes;
    $error.innerHTML = x;
}

我想要的是,如果 <=49,则 html 中的将显示为红色,如果 >=50 && <85,则显示为蓝色,如果 >=85,则显示为绿色。我不知道我是否应该创建一个不同的函数,或者我只需要向该函数添加几行带有 if 公式的行。我试过了,但 id 没有用。

谢谢。

4 个答案:

答案 0 :(得分:1)

你可以试试这个。

 var div = document.getElementById( 'myDiv' );
    if (score >= 85) {
        div.style.color = 'blue';
    }

喜欢

答案 1 :(得分:1)

const color = x <= 49 ? "#f00" : x >= 85 ? "#0f0" : "#00f";

$error.style.color = color;
**or**
document.querySelector("#error").style.color = color; 

我认为“$error”意味着您正在使用jquery,而我不熟悉它,因此如果第一个选项不起作用,则第二个选项会起作用

答案 2 :(得分:1)

请按照下面的 showScore() 函数进行操作。

function showScore () {
    if (!numNotes) return;
    const perr = errorCount * opt.pnlerr, ptim = lateNotes * opt.pnltim;
    var score = 100 * (goodNotes - perr - (opt.tmng ? ptim : 0)) / numNotes;
    var color = "red";
    if (score < 0) score = 0;
    if(score<=49)
      color = "red";
    else if(score>=50 && score<85)
      color = "blue";
    else
      color = "green";
    var x = '<span style="color:'+color+'">'+score.toFixed (0) + '%</span>';
    if (opt.scal)
        x = goodNotes +'-'+ perr + (opt.tmng ? '-'+ ptim : '') +'='+ x +' of '+ numNotes;
    $error.innerHTML = x;
}

答案 3 :(得分:0)

试试这个

let element = document.querySelector("#error");
let score = 20;
element.innerText = score;
if (score > 0) {
  element.style.color = "red"
}
if (score > 50) {
  element.style.color = "blue"
}
if (score > 85) {
  element.style.color = "green"
}
<div id="error">0</div>

相关问题