我正在尝试创建一个 Div,它可以有大约 100 种不同的色调,具体取决于变量的值,在本例中是“投票”。赞成票越多,按钮越红。反对票越多,按钮越蓝。
我可以轻松地用 8 个类创建这样的函数:
$scope.divColor = function (votes) {
if (votes < 60)
return "blue60";
else if (votes >= 60 && votes <= 69)
return "blue70";
else if (votes >= 70 && votes <= 79)
return "blue80";
else if (votes >= 80 && votes <= 89)
return "blue90";
else if (votes >= 90 && votes <= 99)
return "red100";
else if (votes >= 100 && votes <= 109)
return "red110";
else if (votes >= 110 && votes <= 119)
return "red120";
else if (votes >= 120)
return "red130";
}
但是无论如何在某处有一个变量使用投票值来设置实际的背景颜色而不是类?
最佳答案
设置从红色到蓝色的 1000% 渐变背景,然后当投票更新时,只需更改其在 javascript 上的位置:document.getElementById("element").style.backgroundPosition = "0% 50%";
。其中最小值(红色):0% 0%
中间值(紫色):0% 50%
最大值(蓝色):0% 100%
更新:如您在下面的评论中所见,请使用“100000%”而不是“1000%”以避免注意到任何渐变阴影。
function test(){
var votes = document.getElementById("test").value;
document.getElementById("testobj").style.backgroundPosition = "0% " + votes + "%";
}
.square {
width:100px;
height:100px;
background: linear-gradient(0deg, skyblue, tomato);
background-size: 100000% 100000%;
float:left;
line-height: 100px;
text-align: center;
outline: 2px solid black;
}
input {
margin-left: 5px;
width: 100px;
display: inline-block;
vertical-align: middle;
}
.A {
background-position:0% 0%;
}
.B {
background-position:0% 50%;
}
.C {
background-position:0% 100%;
}
.D {
width:100px;
height:100px;
background: linear-gradient(0deg, skyblue, tomato);
background-size: 100000% 100000%;
display: inline-block;
line-height: 100px;
text-align: center;
outline: 2px solid black;
}
<div class="square A">0%</div>
<div class="square B">50%</div>
<div class="square C">100%</div>
<input id=test type="range" name="votes" min="0" max="100" oninput="test()">
<div id=testobj class="D">Slider test</div>
关于javascript - 根据小增量的值更改 Div 类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35587492/