我正在尝试更改所选选项的文本颜色。它在 IE 中工作,但在 Firefox 中不工作。
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("option:selected").css("color", "green");
});
</script>
</head>
<body>
<select id="mySelect">
<option selected="selected">option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
</body>
</html>
已更新
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<script type="text/javascript">
$(document).ready(function(){
$("select").css("color", "green").focus(function() {
$(this).css('color', 'black');
}).blur(function() {
$(this).css('color', 'green');
});
});
</script>
</head>
<body>
<select id="mySelect">
<option selected="selected">option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
</body>
</html>
更新 2
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<style type="text/css">
select.green{
color: green;
}
option {
color: black;
}
</style>
<script type="text/javascript">
$(document).ready(function(){
var green = $('option:selected', 'select').data('green');
if (green) {
$('select').addClass('green');
}
$('select').change(function() {
var green = $('option:selected', this).data('green');
if (green) {
$('select').addClass('green');
}
else {
$('select').removeClass('green');
}
});
});
</script>
</head>
<body>
<select id="mySelect">
<option selected="selected" data-green="true">option 1</option>
<option>option 2</option>
<option>option 3</option>
</select>
</body>
</html>
最佳答案
这可能不是您正在寻找的解决方案,但您可以在 css 中做到这一点:
option[selected] {
color: green;
}
这只适用于支持属性选择器的浏览器 (IE7+)
编辑:
阅读您的评论后,我了解您想要实现的目标。您希望将 select
和所选元素(option
)设为绿色(其余为黑色)。您可以使用以下 CSS 代码执行此操作:
select {
color: green;
}
option[selected] {
color: green;
}
option {
color: black;
}
查看我的 JSFiddle .但是,在您选择不同的选项后,颜色不会改变。
关于jquery - 在 Firefox 中更改 <option> 的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9403817/