【问题标题】:HTML change font color of text in option with CSS (Mac OS, Chrome)HTML 使用 CSS 更改文本的字体颜色(Mac OS、Chrome)
【发布时间】:2018-12-03 16:43:32
【问题描述】:

我试图像这样更改选项的颜色,但似乎没有更改样式中指定的颜色。我在这里错过了什么?

<select name="test" >
  <option value="green" style="color:green;">this is green</option>
  <option value="red" style="color:red;">this is red</option>
</select>

编辑:在我的计算机 Mac OS 上运行的结果截图(Chrome 版本 67.0.3396.79(官方构建)(64 位))

【问题讨论】:

标签: html css macos google-chrome


【解决方案1】:

您可以尝试使用颜色代码而不是“红色”/“绿色”

请参考以下颜色代码, https://www.w3schools.com/cssref/css_colors.asp

试试下面的代码,

<font color="#FF0000">This is some text!</font>

【讨论】:

  • 使用 css HTML 使用 CSS 更改选项中文本的字体颜色
  • font 元素已被弃用多年(在 HTML5 中已过时)。不要使用或推荐它。
【解决方案2】:

更新 01

试试这个,实际上是一样的,但是看看 mac 上的 chrome 是否对此感到满意 :-)

function selectionChanged(){
    var selectElement = document.getElementById('test');
    var selectedOption = selectElement.selectedIndex;
    selectElement.style.color = selectElement.options[selectedOption].value;
}
<select name="test" id="test" onchange="selectionChanged()" style="color: green">
    <option value="green" style="color:green;">this is green</option>
    <option value="red" style="color:red;">this is red</option>
</select>

原答案:

也许你需要的是……

<select name="test" id="test" onchange="document.getElementById('test').style.color = document.getElementById('test').options[document.getElementById('test').selectedIndex].value" style="color: green">
  <option value="green" style="color:green;">this is green</option>
  <option value="red" style="color:red;">this is red</option>
</select>
  1. 请注意,select 元素的绿色是硬编码的,因为第一个/默认选项是绿色
  2. 然后onchange of select 将根据所选选项重新应用样式。 (你也可以在 JS 中创建一个特定的函数,但如果你的需求不会增长,这段代码就可以解决问题)

【讨论】:

  • 使用 mac + Chrome 的 OP。你在这个环境下测试过吗?
  • 这不适用于 Mac OS (Chrome)。但它适用于 Firefox
  • 啊,我的错,我无法访问 mac,它在 chrome Windows 上对我有用。如果可行的话,也许我会很快用替代方法更新答案。
【解决方案3】:

我认为您想根据选择更改选择的颜色。因此;

<select name="test" id="test" onchange="changeColor()">
  <option value="green" style="color:green;">this is green</option>
  <option value="red" style="color:red;">this is red</option>
</select>
<script type="text/javascript">
   function changeColor() {
    document.getElementById("test").style.color = document.getElementById("test").value;
   }
</script>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-04-04
    • 1970-01-01
    • 2019-02-06
    • 1970-01-01
    • 1970-01-01
    • 2015-12-31
    • 1970-01-01
    相关资源
    最近更新 更多