Javascript读取row backgroundColor为rbg,但不会设置backgroundColor

问题描述:

我想切换表格行的颜色。最初,我想记住该行是什么颜色。Javascript读取row backgroundColor为rbg,但不会设置backgroundColor

var bg = table.rows[I].style.backgroundColor; 

在一个特定行的BG可能包含 “RGB(240,255,248)”

如果我随后写:

table.rows[I].style.backgroundColor = bg; 

所述的backgroundColor未设置。

如果我写:

table.rows[I].style.backgroundColor = '#F0FFF8'; 

的backgroundColor时设置。

为什么JavaScript将backgroundColor读取为rgb值,但不会将backgroundColor设置为该rgb值?如何将JavaScript读取的rgb值转换为可写入的值?

请注意 - 我不想在此时开始设置CSS样式。当前的代码都是从一个非常复杂的.aspx页面生成的。

+1

定义。 – Christophe

+0

不,因为如果我这样做: // var bg = table.rows [I] .style.backgroundColor; var bg ='#F0FFF8'; 它工作正常。 它的工作如果我写: if(bg =='rgb(rgb(240,255,248)')table.rows [I] .style.backgroundColor ='#FOFFF8'; –

+0

然后可能会设置一个现场演示,例如在jsfiddle.net上,向我们展示行为。 – Christophe

本质上没有什么会阻止Javascript使用RGB(r,g,b)表示法设置背景颜色。你的问题在别处。

例如,以下内容完全有效,并且会将页面的背景颜色设置为浅蓝色阴影。

document.body.style.backgroundColor = 'rgb(240, 255, 248)'; 

这里有一个的jsfiddle来证明这一点:http://jsfiddle.net/4Gcm9/1

我也测试了以下和它的工作就好了:你可能正在使用范围的BG以外的地方是

<table> 
    <tbody> 
    <tr> 
     <td>Hello</td> 
     <td>World</td> 
    </tr> 
    <tr id="tablerow" bgcolor="#ff0000"> 
     <td>From</td> 
     <td>HTML</td> 
    </tr> 
    </tbody> 
</table> 
<script type="text/javascript"> 
    var tableRow = document.getElementById('tablerow'); 

    var bg = tableRow.style.backgroundColor; 
    tableRow.style.backgroundColor = '#00ff00'; 

    var p = prompt("Press enter", "ENTER"); 

    tableRow.style.backgroundColor = bg; 
</script>