Javascript 在下拉列表中更改所选选项的颜色

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6654530/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 22:38:50  来源:igfitidea点击:

Change the color of selected option in dropdown

javascripthtmlcss

提问by King Julien

Possible Duplicate:
HTML <select> selected option background-color CSS style

可能的重复:
HTML <select> 选择的选项背景颜色 CSS 样式

How can I change the color of the selected option in dropdown list? I need to change the color of the option which is visible when the dropdown is closed...

如何更改下拉列表中所选选项的颜色?我需要更改下拉列表关闭时可见的选项的颜色...

回答by pimvdb

You can get the value from select.options[select.selectedIndex], so this might fit your needs: http://jsfiddle.net/6VhK8/.

您可以从 获取值select.options[select.selectedIndex],因此这可能符合您的需求:http: //jsfiddle.net/6VhK8/

var select = document.getElementById('select');
select.onchange = function() {
    for(var i = 0; i < select.options.length; i++) {
        if(i == select.selectedIndex) {
            select.options[i]
            .style.backgroundColor = 'red';
        } else {
            select.options[i]
            .style.backgroundColor = '';
        }
    }
}