你可以使用线性渐变。
如果百分比为 40%:
table{
background: -webkit-gradient(linear, left top, right top, color-stop(40%,#F00), color-stop(40%,#00F));
background: -moz-linear-gradient(left center, #F00 40%, #00F 40%);
background: -o-linear-gradient(left, #F00 40%, #00F 40%);
background: linear-gradient(to right, #F00 40%, #00F 40%);
}
演示
所以,在 JavaScript 中,
var percentage=40,
col1="#F00",
col2="#00F";
var t=document.getElementById('table');
t.style.background = "-webkit-gradient(linear, left top,right top, color-stop("+percentage+"%,"+col1+"), color-stop("+percentage+"%,"+col2+"))";
t.style.background = "-moz-linear-gradient(left center,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
t.style.background = "-o-linear-gradient(left,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
t.style.background = "linear-gradient(to right,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
演示
如果您想以不同的方式将其应用于每一行:
var col1="#F00",
col2="#00F";
var els=document.getElementById('table').getElementsByTagName('tr');
for (var i=0; i<els.length; i++) {
var percentage = Number(els[i].getElementsByTagName('td')[1].firstChild.nodeValue);
els[i].style.background = "-webkit-gradient(linear, left top,right top, color-stop("+percentage+"%,"+col1+"), color-stop("+percentage+"%,"+col2+"))";
els[i].style.background = "-moz-linear-gradient(left center,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)" ;
els[i].style.background = "-o-linear-gradient(left,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)";
els[i].style.background = "linear-gradient(to right,"+col1+" "+percentage+"%, "+col2+" "+percentage+"%)" ;
}
问题是tr
在 Firefox 和 Opera 上设置背景效果很好,但在 Chrome 上,渐变应用于每个单元格。
添加此代码可以解决此问题(请参阅https://stackoverflow.com/a/10515894):
#table td {display: inline-block;}
演示