更改< select>的颜色取决于其值-仅CSS(?) [英] Changing the color of a <select> depending on its value - CSS only(?)

查看:57
本文介绍了更改< select>的颜色取决于其值-仅CSS(?)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个带有内部某些选项的HTML select元素:

I have an HTML select element with some options inside:

<select class = "myRed" id="mySelect" onchange="onSelectChange()">
    <option selected value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
</select>

我希望选择对象的文本颜色为0时为红色,否则为黑色。我可以通过JavaScript做到这一点:

I would like the text color of the select object to be red when its value is 0, black otherwise. I could be able to do this through JavaScript:

function onSelectChange(){
    if (document.getElementById('mySelect').value == 0){
        document.getElementById('mySelect').className = 'myRed';
    } else {
        document.getElementById('mySelect').className = 'myBlack'
    }
}

其中

.myRed{color:red;}

.myBlack{color:black;}

但是,有人告诉我这可以通过仅CSS,不使用JavaScript。除了使用JS,我无法考虑其他任何方式。有人可以建议吗?

However, I've been told this is somehow reachable through CSS only, without using JavaScript. I cannot think about any other way than using JS. Could anyone please advise?

推荐答案

您可以使用必需并将空值分配给第一个选项:

You can use required and assign empty value to the first option:

<select class="mySelect" required>
    <option value="">0</option>
    <option value="1">1</option>
</select>

css:

.mySelect { font-size: 2em; }
.mySelect option { color: green; }
.mySelect option[value=""] { color: red; }
.mySelect:invalid { color: red; }

检查 fiddle

这篇关于更改&lt; select&gt;的颜色取决于其值-仅CSS(?)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆