您可以使用线性梯度.
如果百分比是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
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上,渐变应用于每个单元格.
#table td {display: inline-block;}