1

如何仅将 CSS 背景颜色应用于所选选项?如果我将一个类应用于选择对象,它会设置所有选项的样式。如果我将所需的类应用于选项,则在展开选择框时,我可以看到所有选项的样式都很好。但是,当“选择”框折叠时,所选选项的样式消失。我在最新版本的 Chrome 和 Firefox 中观察到这种行为。

这是一些超级基本的示例代码。如果没有 jQuery,所选选项始终显示为无样式。使用 jQuery,一旦选择了“已修改”选项,所有选项的样式都将被设置为“已修改”。我一直无法找到解决这个问题的方法......有什么想法吗?

我不想更改选项的样式。只有在选择任何给定选项时才能看到其样式,而不会覆盖其他选项的样式。

<style>
  select.modified,
  option.modified{
    background-color: red;
  }
</style>

<select id="example">
  <option value="bird" class="modified">bird</option>
  <option value="cat">cat</option>
  <option value="dog" class="modified">dog</option>
</select>

<script>
  $('#example').on('change',function(){
    $(this).prop('class',$(this).find('option:selected').prop('class'));  
  });
</script>
4

5 回答 5

1
select option.modified { color: red; /*something*/ }

$('#example').on('change', function(){
    $(this).find('option').removeClass('modified');
    $(this).find('option:selected').addClass('modified');
});
于 2012-08-31T17:50:24.843 回答
1

试试这个:

$('#example').on('change',function(){
   $(':selected', this).addClass('modified').siblings().removeClass('modified')
});

option.modified{
   background-color: red;
}

小提琴

于 2012-08-31T17:54:33.037 回答
0

您的事件在整个selected#example列表中,因此它的所有选项自然会得到背景,因为它们位于选择中。尝试将您的事件与选项标签联系起来。

此外,您的第二条规则将颜色应用于所有选项标签和虚构modified标签。通过用,a替换,.你会做你的意思 - 只有那些选项与modified类。

于 2012-08-31T17:49:56.137 回答
0

好吧,在阅读了评论之后,我认为您真的想要这些方面的东西。

$('#example').on('change', function() {
    console.log(this.options[this.selectedIndex].style);
});​

或者没有 jQuery

document.getElementById('example').onchange = function() {
    console.log(this.options[this.selectedIndex].style);
};

这将为您提供CSSStyleDeclaration所有当前规则。请记住,十六进制值以 rgb 形式返回。

演示:http:
//jsfiddle.net/rlemon/Qu5Xa/1/

或者另一种选择是返回 className....

document.getElementById('example').onchange = function() {
    console.log(this.options[this.selectedIndex].className);
};

或 jQuery

$('#example').on('change', function() {
    $(this.options[this.selectedIndex]).attr('class'); // however I would still not even bother wrapping this up in jQuery and just use this.options[this.selectedIndex].className
});​
于 2012-08-31T18:22:40.110 回答
0

我找到了解决这个问题的最佳方法。基本上我必须从选定的焦点选项中删除任何类,并将其添加回模糊的那些类。这似乎很好地解决了这个问题。

<script>
  $('#example').on('change',function(){
    // do whatever needs to be done
    $(this).blur();
  }).on('focus',function(){
    $(this).removeClass($(this).find('option:selected').prop('class'));
  }).on('blur',function(){
    $(this).addClass($(this).find('option:selected').prop('class'));
  });
</script>
于 2012-08-31T20:16:04.547 回答