你基本上描述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