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リスト全体に含まれているので、当然のことながら、すべてのオプションは選択に座っているため、背景を取得します。イベントをオプションタグに関連付けてみてください。

また、2番目のルールは、すべてのオプションタグと架空のmodifiedタグに色を適用します。をに置き換えること,で、.あなたはあなたが意味することをするでしょう-それらのオプションだけが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により、現在のすべてのルールが表示されます。16 進値は 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 に答える