gpt4 book ai didi

javascript - 如何更改同一行中显示的特定变量的颜色?

转载 作者:行者123 更新时间:2023-12-01 00:34:20 25 4
gpt4 key购买 nike

是否可以在不改变“Solution”颜色的情况下改变val的颜色并让它们显示在同一行(代码如下所示)?

result.innerText = "Solution:" + val.toFixed(2);

我知道你可以添加

result.style="color:red";

但是当我运行时,这会改变整行的颜色,包括“解决方案:”;

<div id="result" align ="center"></div>

编辑:我通过添加伪元素和类进行了更改,但除了“解决方案”之外没有显示任何内容

        val = sumsc/sumcr;
var result = document.querySelector('#result');
if(isNaN(sumsc/sumcr)){
val=0.00;
result.innerText = val.toFixed(2);
result.className = "white";


else if(val<3 & val>0.1){

result.innerText = val.toFixed(2);
result.className = "red";
}
else if(val>3 & val<3.5){

result.innerText = val.toFixed(2);
result.className = "pink";
}
else if(val>3.5){

result.innerText = val.toFixed(2);
result.className = "green";
}

        #result{
text-align:center;
}

#result::before {
content: "Solution: ";
color: black;
}

.white {
color: white;
}
.red {
color: red;
}
.pink{
color: pink;
}
.green{
color: green;
}

最佳答案

用跨度包围 val 并向其添加样式应该可以:

result.innerHTML = 'Solution: <span class="red">' + val.toFixed(2) + '</span>';
.red {
color: red;
}

关于javascript - 如何更改同一行中显示的特定变量的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58258195/

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