我能实现这个目标吗?如果用户将该字段留空,我想获取原始值。
这就是我到目前为止所得到的。 Jsfiddle Demo
这是我的代码
$(document).ready(function() {
var field = $('input[type="text"]');
field.focus(function() { //Empty the field on focus
var thisValue = $(this).val();
$(this).attr("value", "");
});
field.blur(function() { //Check the field if it is left empty
if ($(this).val() == "") {
//alert('This field can not be left empty');
$(this).val(thisValue);
}
});
});
最佳答案
您本质上是在描述placeholder
attribute ,所有主要浏览器都原生支持。但是,较旧的浏览器不支持它。为了获得更广泛的支持,您需要填充对此属性的支持。网上有很多选项可以为您执行此操作,但如果您愿意,也可以自己执行此操作。
本质上,您希望允许自己和其他人使用标准标记:
<input name="fname" placeholder="First Name">
使用 jQuery,您可以响应任何对象的 focus
和 blur
(或 focusin
和 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));
这个特定的垫片仅提供基本功能。其他人可能会扩展支持以在使用占位符值时更改字体颜色,以及使占位符值保持可见直到您开始键入(此方法只是在焦点上立即将其删除)。
关于如果字段留空,Jquery 返回模糊时的原始值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10393934/