你基本上描述placeholder
attribute,這是在所有主流瀏覽器原生支持。但是,舊版瀏覽器不支持它。爲了更廣泛的支持,您需要墊片支持此屬性。網上有很多選項可以幫你做到這一點,但如果你喜歡,你可以自己做。
基本上你想要讓自己和他人,使用標準的標記:
<input name="fname" placeholder="First Name">
使用jQuery你想對具有placeholder
屬性的元素的focus
和blur
(或focusin
和focusout
)響應事件。如果一個元素被聚焦並且具有佔位符值,則清除該元素。如果元素模糊且爲空,則提供佔位符值。
這是一個有點冗長,但我已經添加了註釋,以幫助在以下邏輯:
// Written and tested with jQuery 1.8.1
(function ($) {
// Play nice with jshint.com
"use strict";
// Abort if browser already supports placeholder
if ("placeholder" in document.createElement("input")) {
return;
}
// Listen at the document level to work with late-arriving elements
$(document)
// Whenever blur or focus arrises from an element with a placeholder attr
.on("blur focus", "[placeholder]", function (event) {
// Determine the new value of that element
$(this).val(function (i, sVal) {
// First store a reference to it's placeholder value
var placeholder = $(this).attr("placeholder"), newVal = sVal;
// If the user is focusing, and the placehoder is already set
if (event.type === "focusin" && sVal === placeholder) {
// Empty the field
newVal = "";
}
// If the user is blurring, and the value is nothing but white space
if (event.type === "focusout" && !sVal.replace(/\s+/g, "")) {
// Set the placeholder
newVal = placeholder;
}
// Return our new value
return newVal;
});
})
// Finally, when the document has loaded and is ready
.ready(function() {
// Find non-autofocus placeholder elements and blur them
// This triggers the above logic, which may provide default values
$(":input[placeholder]:not([autofocus])").blur();
});
}(jQuery));
這種特殊的墊片只提供基本功能。其他人可能會擴展對使用佔位符值時更改字體顏色的支持,以及在開始鍵入之前將佔位符值保持可見(此方法僅在焦點上立即將其刪除)。
很好,但你冒這個險的文本框的值更改腳本的默認值複製到'data'緩存之前。 – gdoron
@gdoron我在OP提供的內容之外不做任何假設。由於OP正在訪問該值,因此我覺得有必要這樣做。 – Sampson
不要誤解我的意思,我非常喜歡你的答案!但應該注意_「風險」_,所以我注意到:) :) – gdoron