您本质上是在描述所有主要浏览器都原生支持的placeholder
属性。但是,旧浏览器不支持它。要获得更广泛的支持,您需要对此属性进行填充支持。网上有很多选项可以为您执行此操作,但如果您愿意,您可以自己执行。
本质上,您希望允许自己和他人使用标准标记:
<input name="fname" placeholder="First Name">
使用 jQuery,您将响应具有该属性的任何元素的focus
and blur
(or focusin
and focusout
) 事件。placeholder
如果一个元素获得焦点,并且具有占位符值,则清除该元素。如果元素模糊且为空,则提供占位符值。
这有点冗长,但我添加了注释以帮助遵循逻辑:
// 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));
这个特殊的垫片只提供基本功能。其他人可能会扩展支持以在使用占位符值时更改字体颜色,以及在您开始键入之前保持占位符值可见(这种方法只是在焦点上立即将其删除)。