html里面颜色用百分比,CSS设置背景颜色表行的宽度只是一个百分比(CSS to set the background co...

本文介绍如何使用线性渐变背景,并提供了JavaScript实现方法。针对不同浏览器的兼容性问题进行了详细说明。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

你可以使用线性渐变。

如果百分比为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梯度应用到每个细胞。

此问题可以固定添加该代码(参见https://stackoverflow.com/a/10515894 ):

#table td {display: inline-block;}

演示

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值