我想更改下拉列表名称的正面颜色。这里有2个下拉名单1.医生姓名1(折扣10%)和2.医生姓名2(折扣15%)。但我想改变字体颜色只有(折扣10%) (字体颜色红色)和(折扣15%)(字体颜色蓝色)。怎么改变这个?请帮我解决这个问题
<html>
<head>
</head>
<body>
<select name="">
<option value="" >Select Doctor Name</option>
<option value="1">Doctor Name 1 (Discount 10%)</option>
<option value="2">Doctor Name 2 (Discount 15 %)</option>
</select>
</body>
<html>
答案 0 :(得分:0)
我会将JavaScript用于此解决方案,因为如果您有很多选项,代码更容易维护,您还可以调整所选项目的颜色,这是纯CSS无法做到的。这是我的解决方案:
var colorSelect = document.getElementById('colorSelect');
// initialises all colors to the value given by data-color or black
function initColorSelect() {
var options = colorSelect.getElementsByTagName('option');
var selIndex = colorSelect.selectedIndex;
for (var i = 0; i < options.length; ++i) {
var color = '#000';
if (options[i].hasAttribute('data-color')) {
color = options[i].dataset.color;
}
options[i].style.color = color;
if (i == selIndex) colorSelect.style.color = color;
}
}
// changes the color of the selected item
function colorSelectChanged() {
var option = this.options[this.selectedIndex];
var color = '#000';
if (option.hasAttribute('data-color')) {
color = option.dataset.color;
}
colorSelect.style.color = color;
}
window.addEventListener('load', initColorSelect, false);
colorSelect.addEventListener('change', colorSelectChanged, false);
<body>
<select id="colorSelect">
<option value="">Select Doctor Name</option>
<option value="1" data-color="#f00">Doctor Name 1 (Discount 10%)</option>
<option value="2" data-color="#00f">Doctor Name 2 (Discount 15 %)</option>
</select>
</body>