繁体   English   中英

Javascript:设置BackgroundColor <select>项目

[英]Javascript: Set BackgroundColor of <select> item

以下代码在FF和Chrome中工作正常,但该设置在IE8中不起作用:-(

<!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中得到一个有效的对象:[object CSSStyleDeclaration]

保罗是完全正确的。

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

而不是使用

var selectValue = selectElement.value;

我现在用

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

它的工作原理!

谢谢保罗!

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

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

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

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM