Movatterモバイル変換


[0]ホーム

URL:


  1. 面向开发者的 Web 技术
  2. CSS:层叠样式表
  3. CSS 参考
  4. 选择器
  5. :placeholder-shown

此页面由社区从英文翻译而来。了解更多并加入 MDN Web Docs 社区。

View in EnglishAlways switch to English

:placeholder-shown

Baseline Widely available

This feature is well established and works across many devices and browser versions. It’s been available across browsers since 2020年1月.

:placeholder-shownCSS伪类表示当前显示占位符文本的任何<input><textarea> 元素。

尝试一下

label {  display: block;  margin-top: 1em;}input:placeholder-shown {  background-color: ivory;  border: 2px solid darkorange;  border-radius: 5px;}
<form>  <label for="name">Full Name:</label>  <input name="name" type="text" />  <label for="email">Email Address:</label>  <input name="email" type="email" placeholder="name@example.com" />  <label for="age">Your age:</label>  <input       name="age"    type="number"    value="18"    placeholder="You must be 18+" /></form>

语法

css
:placeholder-shown {  /* ... */}

示例

基础示例

该示例中,输入框在显示占位符时将应用特殊字体和边框样式。

HTML

html
<input placeholder="在这里输入一些东西!" />

CSS

css
input {  border: 1px solid black;  padding: 3px;}input:placeholder-shown {  border-color: teal;  color: purple;  font-style: italic;}

结果

文本溢出

当表单字段太小时,占位文本可能会以不良方式被裁剪。你可以使用text-overflow 属性来更改溢出文本的显示方式。

HTML

html
<input placeholder="名字、排行和序号" /> <br /><br /><input placeholder="名字、排行和序号" />

CSS

css
#input2:placeholder-shown {  text-overflow: ellipsis;}

结果

自定义输入框

以下示例使用自定义样式突出显示了学生 ID 字段。

HTML

html
<form>  <p>    <label for="name">输入学生姓名:</label>    <input placeholder="学生姓名" />  </p>  <p>    <label for="branch">输入学生分会:</label>    <input placeholder="学生分会" />  </p>  <p>    <label for="sid">输入学生 ID:</label>    <input      type="number"      pattern="[0-9]{8}"      title="8 digit ID"                placeholder="8 digit id" />  </p>  <input type="submit" /></form>

CSS

css
input {  background-color: #e8e8e8;  color: black;}input.studentid:placeholder-shown {  background-color: yellow;  color: red;  font-style: italic;}

结果

规范

Specification
HTML
# selector-placeholder-shown
Selectors Level 4
# placeholder-shown-pseudo

浏览器兼容性

参见

Help improve MDN

Learn how to contribute

This page was last modified on byMDN contributors.


[8]ページ先頭

©2009-2026 Movatter.jp