简体   繁体   English

如何设置HTML5中“选择”的禁用和选定“选项”的样式

[英]How to style the disabled and selected 'option' of a 'select' in HTML5

I'm trying to use the first 'option' of a 'select' tag as a prompt to the user that input is required. 我正在尝试使用“选择”标签的第一个“选项”作为提示用户输入的信息。 So, I'd like the 'select' box to render the selection in a different color if the selected option is disabled. 因此,如果选择的选项被禁用,我希望“选择”框以另一种颜色呈现选择。

So given the following code: 因此,给出以下代码:

<select>
  <option selected="selected" disabled="disabled">Choose best player...</option>
  <option>Walter Payton</option>
  <option>Jim McMahon</option>
  <option>Mike Singletary</option>
  <option>Richard Dent</option>
  <option>Steve McMichael</option>
  <option>Wilber Marshall</option>
</select>

I'd like the page to show the dropdown with "Choose best player..." in the color gray and then change the color if a non-disabled option is chosen. 我希望页面以灰色显示带有“选择最佳播放器...”的下拉菜单,然后如果选择了非禁用选项,则更改颜色。

I'd prefer a css solution if it exists, but after googling for quite some time I'm beginning to be convinced that some JavaScript will be required. 我希望使用css解决方案(如果存在),但是在搜索了一段时间后,我开始确信需要一些JavaScript。 Any simple solutions out there? 有没有简单的解决方案?

Here's a codepen with this preloaded. 这是一个预装了此代码的codepen

I think you need a little javascript: 我认为您需要一些JavaScript:

HTML HTML

<select onchange="highlight(this)">
    <option class="invalid" selected="selected" disabled="disabled">Choose best player...</option>
    <option>Walter Payton</option>
    <option>Jim McMahon</option>
    <option>Mike Singletary</option>
    <option>Richard Dent</option>
    <option>Steve McMichael</option>
    <option>Wilber Marshall</option>
</select>

CSS CSS

option.invalid {
    background: #eee;
}

option.valid {
    background: #ff8;
}

JavaScript JavaScript的

function highlight(field){
    field.options[0].className = 'valid';
}

jsFiddle Demo . jsFiddle演示

Pure css you want: 您想要的纯CSS:

select option[disabled="disabled"][selected="selected"]
{text-decoration:underline;}

This will style an option with both disabled and selected set. 这将设置禁用和选定集的选项样式。 However, beware of browser compatability issues. 但是,请注意浏览器的兼容性问题。

Demo 演示

It won't however remove the style when another option is selected. 但是,当选择另一个选项时,它不会删除样式。 According to MDN option:checked should be able to be used, but I have not been able to get it to work reliably ( http://jsfiddle.net/gb35e6yj/ ). 根据MDN option:checked应该可以使用,但是我无法使其可靠地工作( http://jsfiddle.net/gb35e6yj/ )。

I think your difficulty (with a pure css solution) will be targeting your select element based on the attributes of a child element. 我认为您的困难(使用纯CSS解决方案)将基于子元素的属性来定位选择元素。

I would use some javascript to check that selected item isn't disabled and then apply your css. 我会使用一些JavaScript来检查所选项目是否未禁用,然后再应用CSS。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM