:placeholder-shown

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2020 年 1 月⁩ 起,所有主流浏览器均已支持。

:placeholder-shown CSS 伪类表示任何当前正在显示占位符文本<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 id="name" name="name" type="text" />

  <label for="email">Email Address:</label>
  <input id="email" name="email" type="email" placeholder="name@example.com" />

  <label for="age">Your age:</label>
  <input
    id="age"
    name="age"
    type="number"
    value="18"
    placeholder="You must be 18+" />
</form>

语法

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

示例

基本示例

此示例在显示占位符时应用特殊字体和边框样式。

HTML

html
<input placeholder="Type something here!" />

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 id="input1" placeholder="Name, Rank, and Serial Number" /> <br /><br />
<input id="input2" placeholder="Name, Rank, and Serial Number" />

CSS

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

结果

自定义输入字段

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

HTML

html
<form id="test">
  <p>
    <label for="name">Enter Student Name:</label>
    <input id="name" placeholder="Student Name" />
  </p>
  <p>
    <label for="branch">Enter Student Branch:</label>
    <input id="branch" placeholder="Student Branch" />
  </p>
  <p>
    <label for="sid">Enter Student ID:</label>
    <input
      type="number"
      pattern="[0-9]{8}"
      title="8 digit ID"
      id="sid"
      class="student-id"
      placeholder="8 digit id" />
  </p>
  <input type="submit" />
</form>

CSS

css
input {
  background-color: #e8e8e8;
  color: black;
}

input.student-id:placeholder-shown {
  background-color: yellow;
  color: red;
  font-style: italic;
}

结果

规范

规范
HTML
# selector-placeholder-shown
选择器 Level 4
# placeholder-shown-pseudo

浏览器兼容性

另见