问题

Chrome支持 input [type = text] 元素上的"占位符属性">占位符属性(其他人也可以这样做).

但是下面的 CSS 不会蹲到占位符的值:

input[placeholder], [placeholder], *[placeholder] {
    color: red !important;
}
<input type="text" placeholder="Value">

Value 仍会保持灰色而不是红色.

是否有方法可以更改占位符文字的颜色?

我已经为不支持占位符属性的浏览器使用jQuery占位符插件.



解决方法

Implementation

有三种不同的实现:伪元素,伪类,以及无.

  • WebKit, Blink (Safari, Google Chrome, Opera 15+) and Microsoft Edge are using a pseudo-element: ::-webkit-input-placeholder. [Ref]
  • Mozilla Firefox 4 to 18 is using a pseudo-class: :-moz-placeholder (one colon). [Ref]
  • Mozilla Firefox 19+ is using a pseudo-element: ::-moz-placeholder, but the old selector will still work for a while. [Ref]
  • Internet Explorer 10 and 11 are using a pseudo-class: :-ms-input-placeholder. [Ref]

Internet Explorer 9和更低版本不支持 placeholder 属性,而 Opera 12及更低版本不支持任何用于占位符的CSS选择器. / p>

The discussion about the best implementation is still going on. Note the pseudo-elements act like real elements in the Shadow DOM. A padding on an input will not get the same background color as the pseudo-element.

CSS selectors

需要用户代理来忽略具有未知选择器的规则.请参见选择器级别3 :

a group of selectors containing an invalid selector is invalid.

因此,我们需要为每个浏览器单独制定规则.否则,所有浏览器都会忽略整个组.

::-webkit-input-placeholder { /* WebKit, Blink, Edge */
    color:    #909;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
   color:    #909;
   opacity:  1;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
   color:    #909;
   opacity:  1;
}
:-ms-input-placeholder { /* Internet Explorer 10-11 */
   color:    #909;
}
<input placeholder="Stack Snippets are awesome!">

Usage notes

  • Be careful to avoid bad contrasts. Firefox's placeholder appears to be defaulting with a reduced opacity, so needs to use opacity: 1 here.
  • Note that placeholder text is just cut off if it doesn’t fit – size your input elements in em and test them with big minimum font size settings. Don’t forget translations: some languages need more room for the same word.
  • Browsers with HTML support for placeholder but without CSS support for that (like Opera) should be tested too.
  • Some browsers use additional default CSS for some input types (email, search). These might affect the rendering in unexpected ways. Use the properties -webkit-appearance and -moz-appearance to change that. Example:
    [type="search"] {
        -moz-appearance:    textfield;
        -webkit-appearance: textfield;
        appearance: textfield;
    }



相关问题推荐