2015-04-28 34 views
0

我在我的web应用程序中有一个中继器控件,它包含一个下拉列表,我在change事件中操纵这种下拉行为(通过添加一些自定义样式)。问题是,当我使用jquery css属性来获取背景色值时,它会返回先前设置的值,而不是更新的值。但奇怪的是,当我使用attr属性获取样式属性时,它给了我正确的输出,但显然我不能使用它,因为我需要特定的样式。jQuery的css属性没有检索到正确的值

这里是我的呈现下拉菜单: -

<select name="ct100$rptCurrentData$ct101$ddlIncludeData" class="clsTypes" 
    id="ctl00_rptCurrentDatas_ddlIncludeData_0" style="background-color: transparent;"> 
    <option style="background-color: transparent;" value="-1">Select</option> 
    <option style="background-color: transparent;" value="1">Activity</option> 
    <option style="background-color: rgb(231, 251, 189);" value="2">Proposal</option> 
    <option style="background-color: transparent;" value="3">Both</option> 
</select> 

我使用重写选择下拉菜单的背景色: -

$(this).find('option:selected').css("backgroundColor", '#E7FBBD');` 

而且我们可以在渲染HTML看到,这是更新正常。但我的问题是检索相同的时候,我得到正确的值.attr("style")但不是.css为什么?

$(this).find('option:selected').css('background-color')); //Output-rgb(10, 36, 106) 
$(this).find('option:selected').css('backgroundColor')); //Output-rgb(10, 36, 106) 
$(this).find('option:selected').attr("style")); 
//Output- background-color: rgb(231, 251, 189); 
+0

它与[this](http://stackoverflow.com/questions/3485365/how-can-i-force-webkit-to-redraw-repaint-to-propagate-style-变化/ 3485654#3485654) – BNN

+0

@nadeem - 不! –

回答

0

在这两种情况下,您都会得到正确的值。问题是'背景颜色'总是给出所用颜色的'rgb'值。检查下面的链接。

https://jsfiddle.net/cq3ow57h/3/

$('select').find('option[value="3"]').css("background-color", 'red'); 

$('select').on('change',function(){ 
alert($(this).find('option:selected').css('backgroundColor'));//Output-rgb(10, 36, 106)); 
// $(this).find('option:selected').css('backgroundColor')); //Output-rgb(10, 36, 106); 

alert($(this).find('option:selected').attr("style")); 

}); 

如果你想要的十六进制代码值,而不是RGB,那么你必须把它转换。 How to get hex color value rather than RGB value?

+0

不,事实并非如此。这不是关于'rgb',我对此很好。我已经清楚地解释了我的问题,当我使用css时,它会提取错误的'rgb'。 –

+1

选中此链接。 https://jsfiddle.net/cq3ow57h/3/。它清楚地显示了更新的值。 –

+0

是的,我同意,但它不适合我,我不能依靠小提琴。 IE 11知道,这可能是一个问题,因为代码很好。 –

0

我可能有一个解决方案。如果动画以某种方式改变颜色,那么.css()将不会改变,直到动画完成。和.attr()给你改变颜色的权利。看到没有动画的区别