輸入框提示文字(Placeholder)隨焦點顯示隱藏是經典交互需求。現代瀏覽器原生支持 `placeholder` 屬性,但舊項目仍需 JS 實現。本文對比原生與 JS 方案,提供完整兼容性處理。
<input type="text" placeholder="請輸入您的姓名">
<input type="search" placeholder="搜索商品...">
<textarea placeholder="請輸入反饋內容"></textarea>
優勢:無需 JS、性能最佳、無障礙友好、移動端原生體驗、CSS 可樣式化(`::placeholder`)。
/* 修改提示文字顏色 */
::placeholder { color: #999; opacity: 1; } /* Firefox 19+ */
:-ms-input-placeholder { color: #999; } /* IE 10-11 */
::-ms-input-placeholder { color: #999; } /* Edge */
/* 輸入框聚焦時淡化提示 */
:focus::placeholder { opacity: 0.5; transition: opacity 0.3s; }
// 原理:focus 時若值等於提示文字則清空;blur 時若為空則恢復提示文字
function setupPlaceholder(inputId, placeholderText) {
var input = document.getElementById(inputId);
if (!input) return;
// 初始化
if (!input.value) {
input.value = placeholderText;
input.classList.add("placeholder-active");
}
// 聚焦:清空提示
input.onfocus = function() {
if (this.value === placeholderText) {
this.value = "";
this.classList.remove("placeholder-active");
}
};
// 失焦:恢復提示
input.onblur = function() {
if (this.value === "") {
this.value = placeholderText;
this.classList.add("placeholder-active");
}
};
// 表單提交前清理(防止提交提示文字)
var form = input.form;
if (form) {
form.onsubmit = function() {
if (input.value === placeholderText) {
input.value = "";
}
};
}
}
// 使用
setupPlaceholder("username", "請輸入您的姓名");
setupPlaceholder("search", "搜索商品...");
$.fn.placeholder = function(text) {
return this.each(function() {
var $this = $(this);
var placeholder = text || $this.attr("data-placeholder") || "請輸入內容";
// 初始化
if (!$this.val()) {
$this.val(placeholder).addClass("placeholder");
}
$this.on("focus", function() {
if ($this.val() === placeholder) {
$this.val("").removeClass("placeholder");
}
}).on("blur", function() {
if (!$this.val()) {
$this.val(placeholder).addClass("placeholder");
}
});
// 表單提交清理
$this.closest("form").on("submit", function() {
if ($this.val() === placeholder) $this.val("");
});
});
};
// 使用
$("#username").placeholder("請輸入您的姓名");
$("#search").placeholder("搜索...");
必須在 `form.onsubmit` 中清空等於提示文字的值,或服務端過濾。
// 密碼框無法直接設置 placeholder 顯示明文(安全限制)
// 方案:焦點時動態切換 type