如何使用CSS设置所选选项的样式,而不设置所有其他选项的样式

How style selected option with CSS without styling all the other options?

本文关键字:样式 选项 设置 其他 何使用 CSS      更新时间:2023-09-26

如何将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>

试试这个:

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

option.modified{
   background-color: red;
}

FIDDLE

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

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

您的事件在整个selected#example列表中,因此它的所有选项自然都会成为背景,因为它们在select上SIT。尝试将您的活动与选项标签绑定。

此外,您的第二条规则将颜色应用于所有选项标记和虚构的modified标记。通过用.替换,,您就可以实现您的意思了——只使用modified类的那些选项。

好吧,在阅读了这些评论之后,我认为你真的想要一些类似的东西。

$('#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
});​

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

<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>