如何应用样式到当前选择的选项元素在选择? [英] How to apply style to currently selected option element in select?

查看:93
本文介绍了如何应用样式到当前选择的选项元素在选择?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为 select 的特定选项元素设置 style =color:#D4D4D4。当我设置< option value =TESTstyle =color:#D4D4D4> TEST< / option> 。但是,选择中的当前选中的选项元素(当下拉没有展开时)仍然具有默认字体颜色。如何更改?



更新:



sel.onchange 不会跟踪对选项属性所做的更改。我使用jQuery设置属性,需要更新立即反映在选择。我如何做到这一点?



jQuery

  $('。 form-control option [value ='+ $ scope.environment +']')。attr('style','color:#D4D4D4'); 


解决方案

  var sel = document。 getElementById(sel); function changeSelectColor(){sel.style.color = sel.options [sel.selectedIndex] .style.color;} changeSelectColor(); // Do when readysel.onchange = changeSelectColor; //并在更改后执行 

 < select id = sel> < option value =TEST1style =color:red> TEST1< / option> < option value =TEST2style =color:blue> TEST2< / option> < option value =TEST3style =color:green> TEST3< / option>< / select>   

I need to set style="color: #D4D4D4" to specific option elements of select. When I set <option value="TEST" style="color: #D4D4D4">TEST</option> it successfully changes style when drop down of options is expanded. However the currently selected option element in select (when drop down is not expanded) still has default font color. How to change it?

Update:

Thanks! But sel.onchange is not tracking changes made to attributes of option. I use jQuery to set attribute and need update to be reflected in select immediately. How can I do that?

jQuery

$('.form-control option[value="' + $scope.environment + '"]').attr('style', 'color: #D4D4D4');

解决方案

var sel = document.getElementById("sel");

function changeSelectColor(){
  sel.style.color = sel.options[sel.selectedIndex].style.color;
}

changeSelectColor(); // Do when ready
sel.onchange = changeSelectColor; // And do it on change

  <select id="sel">
    <option value="TEST1" style="color:red">TEST1</option>
    <option value="TEST2" style="color:blue">TEST2</option>
    <option value="TEST3" style="color:green">TEST3</option>
</select>

这篇关于如何应用样式到当前选择的选项元素在选择?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆