2014-02-19 46 views
1

下面的代码集BACKGROUNDCOLOR在FF和Chrome就好了,但是设置不能在IE8 :-(的Javascript:<select>项目

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" 
    "http://www.w3.org/TR/html4/loose.dtd"> 
<html> 
<head> 
<script type="text/javascript"> 
    function changeColor(id) 
    { 
    var selectName = "select" + id; 
    var selectElement = document.getElementById(selectName); 
    var selectValue = selectElement.value; 
    var backColor = '#FFFFFF'; 
    if(selectValue == 'No') 
    { 
     backColor = 'lightcoral'; 
    } 
    else 
    { 
     backColor = 'lightgreen'; 
    } 
    selectElement.style.backgroundColor = backColor; 
    } 
</script> 
</head> 
... 
<form name="update" action="update.php" method="post"> 
<select name="select1" id="select1" onchange="changeColor(1);" > 
    <option>No</option> 
    <option selected="selected">Yes</option> 
</select> 
... 

工作在IE8的下拉是不会改变它的回。颜色这个功能本身虽然称为

如果我这样做

alert(selectElement.style); 

我在IE8中得到有效的对象:[对象的CSSStyleDeclaration]

+2

使用'selectElement.options [selectElement.selectedIndex] .value'得到当前选定的价值 –

+0

Thx Paul,就是这样! –

回答

-1

有很多特定于浏览器的CSS属性。 使用jquery没有这些问题。

+2

这不是答案,而是评论 –

+0

为什么不呢?答案是:使用jquery没有这些问题 – Serginho

+0

告诉用户只是去使用jQuery不能解决他的问题,因此不是他的解决方案的答案。然而,这是一个合适的评论,因为这是一个建议或绕过他的问题。这有帮助吗? –

2

保罗是完全正确的。

我正要写,我注意到,错误在于完全elsewere

而不是使用

var selectValue = selectElement.value; 

的我现在用

var selectValue = selectElement.options[selectElement.selectedIndex].value; 

和它的作品!

谢谢保罗!

2

设置backgroundColor直接在<option> -elements:

for (var i=0;i<selectElement.children.length;i++) { 
    selectElement.children[i].style.backgroundColor = backColor; 
} 

看到工作小提琴 - >http://jsfiddle.net/4eqx5/

+0

更新,小提琴着色的选项,但没有颜色他们时,一个新的项目被选中 - 这是现在纠正(没有包装在头) – davidkonrad