我正在使用占位符进行文本输入,效果很好。 但是我也想为我的选择框使用一个占位符。 当然,我可以使用以下代码:
<select>
<option value="">Select your option</option>
<option value="hurr">Durr</option>
</select>
但是“选择您的选项”是黑色而不是浅灰色。 因此,我的解决方案可能基于CSS。 jQuery也很好。
这只会使下拉菜单中的选项变为灰色(因此,单击箭头后):
option:first {
color: #999;
}
问题是:人们如何在选择框中创建占位符? 但它已经得到回答,欢呼。
使用此方法会导致所选值始终为灰色(即使在选择实选项后):
select {
color: #999;
}
#1楼
下面的解决方案也可以在Firefox中运行,无需任何JavaScript:
option[default] { display: none; }
<select> <option value="" default selected>Select Your Age</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> </select>
#2楼
我看到了正确答案的迹象,但是综合考虑,这将是我的解决方案:
select { color: grey; } option { color: black; } option[default] { display: none; }
<select> <option value="" default selected>Select your option</option> <option value="hurr">Durr</option> </select>
#3楼
JavaScript的另一种可能性:
$('body').on('change', 'select', function (ev){
if($(this).find('option:selected').val() == ""){
$(this).css('color', '#999');
$(this).children().css('color', 'black');
}
else {
$(this).css('color', 'black');
$(this).children().css('color', 'black');
}
});
#4楼
我遇到了同样的问题,在搜索时遇到了这个问题,在找到适合我的解决方案之后,我想与大家分享一下,以防有人可以从中受益。
这里是:
HTML:
<select class="place_holder dropdown">
<option selected="selected" style=" display: none;">Sort by</option>
<option>two</option>
<option>something</option>
<option>4</option>
<option>5</option>
</select>
CSS:
.place_holder {
color: gray;
}
option {
color: #000000;
}
JavaScript:
jQuery(".dropdown").change(function () {
jQuery(this).removeClass("place_holder");
});
在客户做出第一选择之后,就不需要灰色了,因此JavaScript代码删除了place_holder
类。
感谢@ user1096901,作为Internet Explorer浏览器的解决方法,如果再次选择第一个选项,则可以再次添加place_holder
类:)
#5楼
对于必填字段,现代浏览器中有一个纯CSS解决方案:
select:required:invalid { color: gray; } option[value=""][disabled] { display: none; } option { color: black; }
<select required> <option value="" disabled selected>Select something...</option> <option value="1">One</option> <option value="2">Two</option> </select>
#6楼
对于上述所有解决方案,但由于HTML规范,这一解决方案似乎最有效:
<select>
<optgroup label="Your placeholder">
<option value="value">Label</option>
</optgroup>
</select>
更新:请原谅我这个错误的答案,这绝对不是select
元素的占位符解决方案,而是打开的select
元素列表下分组选项的标题。
#7楼
我只是在如下所示的option
添加了一个隐藏属性。 对我来说很好。
<select> <option hidden>Sex</option> <option>Male</option> <option>Female</option> </select>
#8楼
这是我的:
select:focus option.holder { display: none; }
<select> <option selected="selected" class="holder">Please select</option> <option value="1">Option #1</option> <option value="2">Option #2</option> </select>
#9楼
您可以在不使用仅使用
HTML
Javascript
情况下执行此操作。您需要设置默认的选择选项disabled=""
和selected=""
然后选择标记required="".
浏览器不允许用户不选择选项就提交表单。
<form action="" method="POST">
<select name="in-op" required="">
<option disabled="" selected="">Select Option</option>
<option>Option 1</option>
<option>Option 2</option>
<option>Option 3</option>
</select>
<input type="submit" value="Submit">
</form>
#10楼
我希望SELECT在选择之前为灰色,因此对于这段HTML:
<select>
<option value="" disabled selected>Select your option</option>
<option value="hurr">Durr</option>
</select>
我添加了以下CSS定义:
select { color: grey; }
select:valid { color: black; }
它可以在Chrome / Safari和其他浏览器中按预期工作,但我没有检查。
#11楼
这是一个效果很好的CSS解决方案。 将内容添加到包含元素之后(并通过绝对位置相对于容器放置)( 通过:after伪类 )。
它从我在指令使用位置( attr(placeholder) )定义的placeholder属性获取文本。 另一个关键因素是指针事件:无 -允许单击占位符文本以传递到选择项。 否则,如果用户单击文本,它将不会下拉。
我自己在自己的select指令中添加了.empty类,但通常我会发现angular为我添加/删除了.ng-empty (我想是因为我在代码示例中注入了Angular 1.2版)。
(该示例还演示了如何在AngularJS中包装HTML元素以创建自己的自定义输入)
var app = angular.module("soDemo", []); app.controller("soDemoController", function($scope) { var vm = {}; vm.names = [{ id: 1, name: 'Jon' }, { id: 2, name: 'Joe' }, { id: 3, name: 'Bob' }, { id: 4, name: 'Jane' } ]; vm.nameId; $scope.vm = vm; }); app.directive('soSelect', function soSelect() { var directive = { restrict: 'E', require: 'ngModel', scope: { 'valueProperty': '@', 'displayProperty': '@', 'modelProperty': '=', 'source': '=', }, link: link, template: getTemplate }; return directive; / function link(scope, element, attrs, ngModelController) { init(); return; / IMPLEMENTATION function init() { initDataBinding(); } function initDataBinding() { ngModelController.$render = function() { if (scope.model === ngModelController.$viewValue) return; scope.model = ngModelController.$viewValue; } scope.$watch('model', function(newValue) { if (newValue === undefined) { element.addClass('empty'); return; } element.removeClass('empty'); ngModelController.$setViewValue(newValue); }); } } function getTemplate(element, attrs) { var attributes = [ 'ng-model="model"', 'ng-required="true"' ]; if (angular.isDefined(attrs.placeholder)) { attributes.push('placeholder="{{placeholder}}"'); } var ngOptions = ''; if (angular.isDefined(attrs.valueProperty)) { ngOptions += 'item.' + attrs.valueProperty + ' as '; } ngOptions += 'item.' + attrs.displayProperty + ' for item in source'; ngOptions += '"'; attributes.push('ng-options="' + ngOptions + '"'); var html = '<select ' + attributes.join(' ') + '></select>'; return html; } });
so-select { position: relative; } so-select select { font-family: 'Helvetica'; display: inline-block; height: 24px; width: 200px; padding: 0 1px; font-size: 12px; color: #222; border: 1px solid #c7c7c7; border-radius: 4px; } so-select.empty:before { font-family: 'Helvetica'; font-size: 12px; content: attr(placeholder); position: absolute; pointer-events: none; left: 6px; top: 3px; z-index: 0; color: #888; }
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script> <div ng-app="soDemo" ng-controller="soDemoController"> <so-select value-property="id" display-property="name" source="vm.names" ng-model="vm.nameId" placeholder="(select name)"></so-select> </div>
#12楼
我目前无法使用其中的任何一个,因为对我而言,这是(1)不需要的,并且(2)需要返回默认可选选项的选项。 因此,如果您使用的是jQuery,这是一个繁重的选择:
var $selects = $('select'); $selects.change(function () { var option = $('option:default', this); if(option && option.is(':selected')) { $(this).css('color', '#999'); } else { $(this).css('color', '#555'); } }); $selects.each(function() { $(this).change(); });
option { color: #555; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select name="in-op"> <option default selected>Select Option</option> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select>
#13楼
这是我的贡献。 Haml + CoffeeScript + SCSS
哈姆
=f.collection_select :country_id, [us] + Country.all, :id, :name, {prompt: t('user.country')}, class: 'form-control'
CoffeeScript
$('select').on 'change', ->
if $(this).val()
$(this).css('color', 'black')
else
$(this).css('color', 'gray')
$('select').change()
SCSS
select option {
color: black;
}
可以通过更改服务器代码并仅根据属性的当前值设置类样式来仅使用CSS,但是这种方式看起来更简单,更简洁。
$('select').on('change', function() { if ($(this).val()) { return $(this).css('color', 'black'); } else { return $(this).css('color', 'gray'); } }); $('select').change();
select option { color: black; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="form-control" name="user[country_id]" id="user_country_id"> <option value="">Country</option> <option value="231">United States</option> <option value="1">Andorra</option> <option value="2">Afghanistan</option> <option value="248">Zimbabwe</option></select>
您可以添加更多CSS( select option:first-child
)以在占位符打开时使其保持灰色,但我对此并不在乎。
#14楼
尝试以下更改:
$("select").css("color", "#757575");
$(document).on("change", "select", function(){
if ($(this).val() != "") {
$(this).css("color", "");
}
else {
$(this).css("color", "#757575");
}
});
#15楼
不需要任何JavaScript或CSS,只需三个属性即可:
<select>
<option selected disabled hidden>Default Value</option>
<option>Value 1</option>
<option>Value 2</option>
<option>Value 3</option>
<option>Value 4</option>
</select>
它根本不显示该选项。 它只是将选项的值设置为默认值。
但是,如果您只是不喜欢与其余颜色相同的占位符,则可以按以下方式内联修复它:
<!DOCTYPE html>
<html>
<head>
<title>Placeholder for select tag drop-down menu</title>
</head>
<body onload="document.getElementById('mySelect').selectedIndex = 0">
<select id="mySelect" onchange="document.getElementById('mySelect').style.color = 'black'" style="color: gray; width: 150px;">
<option value="" hidden>Select your beverage</option> <!-- placeholder -->
<option value="water" style="color:black" >Water</option>
<option value="milk" style="color:black" >Milk</option>
<option value="soda" style="color:black" >Soda</option>
</select>
</body>
</html>
显然,您可以将函数和至少select的CSS分离到单独的文件中。
注意: onload函数可纠正刷新错误。
#16楼
在这里,我修改了大卫的答案 (可接受的答案)。 关于他的回答,他在option
标签上放置了禁用和选择属性,但是当我们还隐藏标签时,它将看起来更好。
通过在option
标签上添加额外的隐藏属性,可以防止在选择“ Durr”选项后重新选择“ Select your option”选项。
<select> <option value="" disabled selected hidden>Select your option</option> <option value="hurr">Durr</option> </select>
#17楼
输入[type="text"]
选择元素的样式占位符
以下解决方案模拟了一个占位符,因为它与input[type="text"]
元素相关:
$('.example').change(function () { $(this).css('color', $(this).val() === '' ? '#999' : '#555'); });
.example { color: #999; } .example > option { color: #555; } .example > option[value=""] { color: #999; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <select class="example"> <option value="">Select Option</option> <option>Option 1</option> <option>Option 2</option> <option>Option 3</option> </select>
#18楼
我对仅使用HTML / CSS的解决方案不满意,因此我决定使用JavaScript创建自定义select
。
这是我在过去30分钟内写的,因此可以进一步改进。
您所要做的就是创建一个包含少量数据属性的简单列表。 该代码自动将列表变成可选的下拉列表。 它还添加了隐藏的input
来保存选定的值,因此可以在表单中使用它。
输入:
<ul class="select" data-placeholder="Role" data-name="role">
<li data-value="admin">Administrator</li>
<li data-value="mod">Moderator</li>
<li data-value="user">User</li>
</ul>
输出:
<div class="ul-select-container">
<input type="hidden" name="role" class="hidden">
<div class="selected placeholder">
<span class="text">Role</span>
<span class="icon">▼</span>
</div>
<ul class="select" data-placeholder="Role" data-name="role">
<li class="placeholder">Role</li>
<li data-value="admin">Administrator</li>
<li data-value="mod">Moderator</li>
<li data-value="user">User</li>
</ul>
</div>
本应为占位符的项目文本显示为灰色。 如果用户想要还原他/她的选择,则可以选择占位符。 同样使用CSS,可以克服select
所有缺点(例如,无法样式化选项)。
// Helper function to create elements faster/easier // https://github.com/akinuri/js-lib/blob/master/element.js var elem = function(tagName, attributes, children, isHTML) { let parent; if (typeof tagName == "string") { parent = document.createElement(tagName); } else if (tagName instanceof HTMLElement) { parent = tagName; } if (attributes) { for (let attribute in attributes) { parent.setAttribute(attribute, attributes[attribute]); } } var isHTML = isHTML || null; if (children || children == 0) { elem.append(parent, children, isHTML); } return parent; }; elem.append = function(parent, children, isHTML) { if (parent instanceof HTMLTextAreaElement || parent instanceof HTMLInputElement) { if (children instanceof Text || typeof children == "string" || typeof children == "number") { parent.value = children; } else if (children instanceof Array) { children.forEach(function(child) { elem.append(parent, child); }); } else if (typeof children == "function") { elem.append(parent, children()); } } else { if (children instanceof HTMLElement || children instanceof Text) { parent.appendChild(children); } else if (typeof children == "string" || typeof children == "number") { if (isHTML) { parent.innerHTML += children; } else { parent.appendChild(document.createTextNode(children)); } } else if (children instanceof Array) { children.forEach(function(child) { elem.append(parent, child); }); } else if (typeof children == "function") { elem.append(parent, children()); } } }; // Initialize all selects on the page $("ul.select").each(function() { var parent = this.parentElement; var refElem = this.nextElementSibling; var container = elem("div", {"class": "ul-select-container"}); var hidden = elem("input", {"type": "hidden", "name": this.dataset.name, "class": "hidden"}); var selected = elem("div", {"class": "selected placeholder"}, [ elem("span", {"class": "text"}, this.dataset.placeholder), elem("span", {"class": "icon"}, "▼", true), ]); var placeholder = elem("li", {"class": "placeholder"}, this.dataset.placeholder); this.insertBefore(placeholder, this.children[0]); container.appendChild(hidden); container.appendChild(selected); container.appendChild(this); parent.insertBefore(container, refElem); }); // Update necessary elements with the selected option $(".ul-select-container ul li").on("click", function() { var text = this.innerText; var value = this.dataset.value || ""; var selected = this.parentElement.previousElementSibling; var hidden = selected.previousElementSibling; hidden.value = selected.dataset.value = value; selected.children[0].innerText = text; if (this.classList.contains("placeholder")) { selected.classList.add("placeholder"); } else { selected.classList.remove("placeholder"); } selected.parentElement.classList.remove("visible"); }); // Open select dropdown $(".ul-select-container .selected").on("click", function() { if (this.parentElement.classList.contains("visible")) { this.parentElement.classList.remove("visible"); } else { this.parentElement.classList.add("visible"); } }); // Close select when focus is lost $(document).on("click", function(e) { var container = $(e.target).closest(".ul-select-container"); if (container.length == 0) { $(".ul-select-container.visible").removeClass("visible"); } });
.ul-select-container { width: 200px; display: table; position: relative; margin: 1em 0; } .ul-select-container.visible ul { display: block; padding: 0; list-style: none; margin: 0; } .ul-select-container ul { background-color: white; border: 1px solid hsla(0, 0%, 60%); border-top: none; -webkit-user-select: none; display: none; position: absolute; width: 100%; z-index: 999; } .ul-select-container ul li { padding: 2px 5px; } .ul-select-container ul li.placeholder { opacity: 0.5; } .ul-select-container ul li:hover { background-color: dodgerblue; color: white; } .ul-select-container ul li.placeholder:hover { background-color: rgba(0, 0, 0, .1); color: initial; } .ul-select-container .selected { background-color: white; padding: 3px 10px 4px; padding: 2px 5px; border: 1px solid hsla(0, 0%, 60%); -webkit-user-select: none; } .ul-select-container .selected { display: flex; justify-content: space-between; } .ul-select-container .selected.placeholder .text { color: rgba(0, 0, 0, .5); } .ul-select-container .selected .icon { font-size: .7em; display: flex; align-items: center; opacity: 0.8; } .ul-select-container:hover .selected { border: 1px solid hsla(0, 0%, 30%); } .ul-select-container:hover .selected .icon { opacity: 1; }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <ul class="select" data-placeholder="Role" data-name="role"> <li data-value="admin">Administrator</li> <li data-value="mod">Moderator</li> <li data-value="user">User</li> </ul> <ul class="select" data-placeholder="Sex" data-name="sex"> <li data-value="male">Male</li> <li data-value="female">Female</li> </ul>
更新 :我对此进行了改进(使用向上/向下/输入键进行选择),对输出进行了一些整理,并将其变成了对象。 电流输出:
<div class="li-select-container">
<input type="text" readonly="" placeholder="Role" title="Role">
<span class="arrow">▼</span>
<ul class="select">
<li class="placeholder">Role</li>
<li data-value="admin">Administrator</li>
<li data-value="mod">Moderator</li>
<li data-value="user">User</li>
</ul>
</div>
初始化:
new Liselect(document.getElementsByTagName("ul")[0]);
进一步检查: JSFiddle ,
GitHub
(重命名)。
更新:我已经再次重写了这个。 除了使用列表,我们还可以使用选择。 这样即使没有JavaScript也可以正常工作(以防被禁用)。
输入:
<select name="role" data-placeholder="Role" required title="Role">
<option value="admin">Administrator</option>
<option value="mod">Moderator</option>
<option>User</option>
</select>
new Advancelect(document.getElementsByTagName("select")[0]);
输出:
<div class="advanced-select">
<input type="text" readonly="" placeholder="Role" title="Role" required="" name="role">
<span class="arrow">▼</span>
<ul>
<li class="placeholder">Role</li>
<li data-value="admin">Administrator</li>
<li data-value="mod">Moderator</li>
<li>User</li>
</ul>
</div>
#19楼
如果您使用的是Angular,请按照以下步骤操作:
<select> <option [ngValue]="undefined" disabled selected>Select your option</option> <option [ngValue]="hurr">Durr</option> </select>
#20楼
用户不应在选择选项中看到占位符。 我建议对占位符选项使用hidden
属性,而对于此选项则不需要selected
属性。 您可以将其放在第一位。
select:not(:valid) { color: #999; }
<select required> <option value="" hidden>Select your option</option> <option value="0">First option</option> <option value="1">Second option</option> </select>
#21楼
我喜欢公认的解决方案 ,并且在没有JavaScript的情况下效果很好。
我只想补充一下我如何对受控选择的React Component采纳这个答案,因为这花了我一些时间才能弄清楚。 合并react-select
并完成它非常简单,但是除非您需要此存储库提供的惊人功能,否则我无需为该项目添加任何千字节,而无需为该项目添加任何千字节。 注意, react-select
通过包含各种inputs
和html
元素的复杂系统来处理react-select
占位符。
在React中,对于受控组件 ,您不能将selected
属性添加到选项中。 React通过select
本身上的value
属性以及更改处理程序来处理select的状态,其中值应与选项本身内的value属性之一匹配。
例如
<select value={this.state.selectValue} onChange={this.handleChange} required={true}>
{options}
</select>
由于这是不适当的,并且实际上会引发错误,无法将selected
属性添加到选项之一,那么该怎么办?
一旦您考虑,答案很简单。 由于我们希望selected
第一个option
以及disabled
和hidden
,因此我们需要做三件事:
- 将
hidden
和disabled
属性添加到第一个定义的option
。 - 将第一个
option
的值设置为空字符串。 - 将
select
的值初始化为一个空字符串。
state = { selectValue = "" } // State or props or their equivalent
// In the render function
<select value={this.state.selectValue} onChange={this.handleChange} required={true}>
<option key="someKey" value="" disabled="disabled" hidden="hidden">Select from Below</option>
{renderOptions()}
</select>
现在,您可以按照上面的指示(或根据需要通过className
)设置选择的样式。
select:invalid { color: gray; }
#22楼
这是一个工作示例,如何使用纯JavaScript实现此功能,该JavaScript在首次单击后处理选项颜色:
<!DOCTYPE html>
<html>
<head>
<style>
#myselect {
color: gray;
}
</style>
</head>
<body>
<select id="myselect">
<option disabled selected>Choose Item
</option>
<option>Item 1
</option>
<option>Item 2
</option>
<option>Item 3
</option>
</select>
<script>
// Add event listener to change color in the first click
document.getElementById("myselect").addEventListener("click", setColor)
function setColor()
{
var combo = document.getElementById("myselect");
combo.style.color = 'red';
// Remove Event Listener after the color is changed at the first click
combo.removeEventListener("click", setColor);
}
</script>
</body>
</html>
#23楼
在Angular中,我们可以添加一个选项作为占位符,该选项可以隐藏在选项下拉列表中。 我们甚至可以添加一个自定义的下拉图标作为背景,以替换浏览器的下拉图标。
技巧是仅在未选择值的情况下 启用占位符 css
/ **我的组件模板* /
<div class="dropdown">
<select [ngClass]="{'placeholder': !myForm.value.myField}"
class="form-control" formControlName="myField">
<option value="" hidden >Select a Gender</option>
<option value="Male">Male</option>
<option value="Female">Female</option>
</select>
</div>
/ **我的Component.TS * /
constructor(fb: FormBuilder) {
this.myForm = this.fb.build({
myField: ''
});
}
/**global.scss*/
.dropdown {
width: 100%;
height: 30px;
overflow: hidden;
background: no-repeat white;
background-image:url('angle-arrow-down.svg');
background-position: center right;
select {
background: transparent;
padding: 3px;
font-size: 1.2em;
height: 30px;
width: 100%;
overflow: hidden;
/*For moz*/
-moz-appearance: none;
/* IE10 */
&::-ms-expand {
display: none;
}
/*For chrome*/
-webkit-appearance:none;
&.placeholder {
opacity: 0.7;
color: theme-color('mutedColor');
}
option {
color: black;
}
}
}
#24楼
这个HTML + CSS
解决方案为我工作:
form select:invalid { color: gray; } form select option:first-child { color: gray; } form select:invalid option:not(:first-child) { color: black; }
<form> <select required> <option value="">Select Planet...</option> <option value="earth">Earth</option> <option value="pandora">Pandora</option> </select> </form>
祝好运...
#25楼
Angular 2解决方案
在选择的顶部创建标签
<label class="hidden-label" for="IsActive"
*ngIf="filterIsActive == undefined">Placeholder text</label>
<select class="form-control form-control-sm" type="text" name="filterIsActive"
[(ngModel)]="filterIsActive" id="IsActive">
<option value="true">true</option>
<option value="false">false</option>
</select>
并应用CSS将其放在顶部
.hidden-label {
position: absolute;
margin-top: .34rem;
margin-left: .56rem;
font-style: italic;
pointer-events: none;
}
pointer-events: none
单击标签时, pointer-events: none
不允许您显示选择内容;选择选项时,标签将隐藏。
#26楼
像这样:
HTML:
<select id="choice">
<option value="0" selected="selected">Choose...</option>
<option value="1">Something</option>
<option value="2">Something else</option>
<option value="3">Another choice</option>
</select>
CSS:
#choice option { color: black; }
.empty { color: gray; }
JavaScript:
$("#choice").change(function () {
if($(this).val() == "0") $(this).addClass("empty");
else $(this).removeClass("empty")
});
$("#choice").change();
工作示例: http : //jsfiddle.net/Zmf6t/
#27楼
非CSS-没有JavaScript / jQuery答案:
<select> <option value="" disabled selected>Select your option</option> <option value="hurr">Durr</option> </select>
#28楼
我偶然发现了这个问题,以下是至少在Firefox和Chrome中有效的方法:
<style> select:invalid { color: gray; } </style> <form> <select required> <option value="" disabled selected hidden>Please Choose...</option> <option value="0">Open when powered (most valves do this)</option> <option value="1">Closed when powered, auto-opens when power is cut</option> </select> </form>
“ 禁用”选项将停止同时使用鼠标和键盘选择<option>
,而仅使用'display:none'
允许用户仍然通过键盘箭头进行选择。 'display:none'
样式只会使列表框看起来“ nice”。
注意:在“占位符”选项上使用空value
属性可以使验证(必填属性)变通使用“占位符”,因此,如果该选项未更改但是必需的,浏览器应提示用户选择一个列表中的选项。
更新(2015年7月):
确认此方法可在以下浏览器中使用:
- 谷歌浏览器-v.43.0.2357.132
- Mozilla Firefox-39.0版
- Safari-v.8.0.7(占位符在下拉列表中可见,但无法选择)
- Microsoft Internet Explorer-v.11(占位符在下拉列表中可见,但不能选择)
- Project Spartan-v.15.10130(占位符在下拉列表中可见,但无法选择)
更新(2015年10月):
我删除了style="display: none"
以支持hidden
的HTML5属性,该属性具有广泛的支持。 hidden
元素具有与display: none
类似的特征display: none
在Safari,Internet Explorer(项目Spartan需要检查)中没有,在下拉菜单中该option
可见,但该option
不可选择。
更新(2016年1月):
当required
select
元素required
它允许使用:invalid
CSS伪类,当您处于select
元素的“占位符”状态时,可以使用它来设置样式。 :invalid
在这里工作,因为占位符option
值为空。
一旦设置了值, :invalid
伪类将被删除。 如果愿意,您也可以选择使用:valid
。
大多数浏览器都支持此伪类。 Internet Explorer 10及更高版本。 这最适合使用自定义样式的select
元素; 在某些情况下(例如,Chrome / Safari中的Mac),您需要更改select
框的默认外观,以便显示某些样式,例如background-color
和color
。 您可以在developer.mozilla.org中找到一些示例以及有关兼容性的更多信息。
Chrome中的本机元素外观Mac:
在Chrome中使用更改后的边框元素Mac: