Set selected option via CSS?

会有一股神秘感。 提交于 2019-12-11 03:08:38

问题


Is it possible to set the selected attribute of an option tag via a CSS class?

I'm wondering if something like the following is possible in a stylesheet:

option.selected {
  selected: true;
}

Then in HTML:

<option class="selected">

Which would have the same effect as setting the selected attribute. Is this technique possible?


回答1:


Nope, CSS only alters the presentation, not the content (although CSS3 does support some modification of content, but not the selection of values.) You'll need to use JavaScript if you can't modify the HTML directly.




回答2:


Not via CSS, but it can be accomplished via javascript.

function setSelects() {

    var allSelects = document.getElementsByTagName("select");
    for (var i = 0; i < allSelects.length; i++) {
        for (var j = 0; j < allSelects[i].options.length; j++) {
            if (allSelects[i].options[j].className == "selected") {

                allSelects[i].selectedIndex = j;
            }
        }
    }
}

window.onload = setSelects;

As other people have pointed out, I'm not sure why you'd want to do it via a CSS class in the first place.




回答3:


option[selected] {background-color:skyblue;color:white;}

in case you want to show the previous marked selection - independend of the changes from the user after displaying a result, the old selected remain sykblue, the new changes are in darkblue.




回答4:


If you use JQuery then you can do something very much along those lines, but not CSS on its own.




回答5:


Selected is not a CSS property. See the spec at http://www.w3.org/TR/CSS2/propidx.html.




回答6:


Yes it is possible, but I am not sure about IE

Below code will change style for default selected item.

           <style>
           option[selected="selected"] {
           color:red;
           font-weight:bold
           }
           </style>

           <select>
           <option value="1">Txt</option>
           <option value="2" selected="selected">Another Txt</option>
           </select>


来源:https://stackoverflow.com/questions/1122036/set-selected-option-via-css

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!