HTML5 placeholder 屬性在 IE9 以下不支援。使用 jQuery 模擬:聚焦時清空預設值,失焦為空則恢復預設值。
$(function() {
$(".input-hint").each(function() {
var $this = $(this);
var defaultVal = $this.val(); // 獲取初始值
$this.focus(function() {
if ($this.val() === defaultVal) {
$this.val("").removeClass("hint-active");
}
}).blur(function() {
if ($this.val() === "") {
$this.val(defaultVal).addClass("hint-active");
}
});
// 表單提交前清理提示值,避免提交到後端
$this.closest("form").submit(function() {
if ($this.val() === defaultVal) $this.val("");
});
});
});
.input-hint { color: #999; } /* 提示態顏色 */
.input-hint.hint-active { color: #999; } /* 同樣樣式,或不加區分 */
.input-hint:focus { color: #333; } /* 聚焦時正常顏色 */
<input type="text" class="input-hint" value="請輸入用戶名" />
<input type="password" class="input-hint" value="請輸入密碼" />
<textarea class="input-hint">請輸入留言內容</textarea>
input::placeholder { color: #999; }。type="password" 在舊 IE 中無法顯示明文提示,需切換 type="text" 再切回,或使用浮動 Label 方案。