单击或悬停时更改下拉列表CSS?

时间:2009-05-15 21:43:56

标签: jquery html events drop-down-menu radio-button

灵感来自https://stackoverflow.com/questions/624102/enable-a-currently-disabled-dropdown-list-when-clicking-the-dropdown-list我尝试了一些东西,并为禁用选择添加了一些灰色背景。

问题在于,当我点击某些选项(禁用了哪个单选按钮)时,下拉列表的背景仍为灰色。

即使没有选中单选按钮,如果单击也可以将其恢复正常(白色)?

你可以在这里看到http://jsbin.com/okuca/

这是我的实际代码:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Test </title>
<style type="text/css">
  label.disabled select { opacity: 0.5; filter: alpha(opacity=50); background-color:#CCC; }

</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

<script type="text/javascript">
  $(function() {
    $('div.formdiv').bind('click',function() {
      $('label.disabled',this).removeClass('disabled');
      $('input:radio',this).attr('checked',true);
      $('div.formdiv').not(this).find('label').addClass('disabled').find('select').attr('selectedIndex',0);
    }).find('label').addClass('disabled');
  });
</script>
</head>

<body>

<div class="formdiv">
  <label for="Name">
    <input id="Name" name="radio1" type="radio" />Name:
    <select name="select1">
      <option value="Rose">Rose</option>
      <option value="Lily">Lily</option>
    </select>
    </br>
  </label> 
</div>

<div class="formdiv">
  <label  for="Colours">
  <input id="Colours" name="radio1" type="radio" />Colour: 
  <select name="select2">
    <option value="Red">Red</option>
    <option value="Green">Green</option>
  </select>
    </label> 
  </br>
 </div> 

<div class="formdiv">  
 <label  for="Sport">
  <input id="Sport" name="radio1" type="radio" />Sport: 
  <select name="select3">
    <option value="Tennis">Tennis</option>
    <option value="Cricket">Cricket</option>
  </select>
  </label> 
  </br>
</div>
  </body>
</html>

您可以在此处进行编辑: http://jsbin.com/okuca/edit

1 个答案:

答案 0 :(得分:4)

问题是点击处理程序在您松开鼠标按钮(并且下拉列表消失)之前不会被触发,因此仍然会应用label.disabled select样式。

有两种方法可以解决这个问题。首先,您可以为:focus添加另一个CSS规则,该规则会覆盖禁用的样式:

label.disabled select:focus { opacity: 1.0; filter: alpha(opacity=100); background-color:white; }

然而,如果你的风格变得更复杂,这可能会让你陷入困境。相反,我建议将您的点击处理程序更改为mousedown处理程序:

$('div.formdiv').bind('mousedown',function() {

这会导致在下拉列表出现之前触发处理程序(以及要删除的类)