[摘要]

jQuery.setTip.js,一个优秀的jQuery插件,通过设置输入框的默认value值来兼容各版本的浏览器。

在前端开发中,提交表单是经常遇到的,一个友好的表单页面(登陆、注册等)对于提升用户体验来说非常重要。在表单的输入框我们一般都会写入提示性的问题,比如“请输入手机号”等。较为理想的状态是,用户看到这段提示性文字,当用户鼠标点击的时候,输入框为空,方便用户填入文字。

一般情况下我们都会使用,但是placeholder作为一个html5属性,它并不支持IE8及以下版本的ie,为此笔者写过《placeholder属性在IE中失效的解决办法》

但最近笔者发现一个优秀的jQuery插件,通过设置输入框的默认value值来兼容各版本的浏览器。这时你可能会说,value值是实实在在存在输入框中的,是默认值,用户需要删除它才能继续输入内容,不友好啊。是的,我们直接在输入框写入确实不太友好,所以这个插件就解决了这个问题啊

html5文本框换行怎么设置 html5文本框默认文字_html5文本框换行怎么设置

当用户打开页面的时候,插件对赋予默认的value值,而当用户点击输入框的时候,插件将会去除value值,实现了placeholder的功能,而又兼容各种浏览器,非常的实用啊。

下面将插件代码放出来

(function($) {
$.fn.setTip = function(options) {
var defaults = {
defaultValue: "",
focusColor: "#000000",
blurColor: "#ccc",
fontSize: "10pt"
}
var options = $.extend(defaults, options);
this.each(function() {
var thisSearch = $(this);
thisSearch.focus(function() {
if (thisSearch.val() == options.defaultValue) {
thisSearch.css("color", options.focusColor);
thisSearch.val("");
}
}).blur(function() {
if ( thisSearch.val() === undefined || thisSearch.val() == '') {
thisSearch.css("color", options.blurColor);
thisSearch.val(options.defaultValue);
}
}).css({ "color": options.blurColor, "font-size": options.fontSize });
if (thisSearch.val() == 'undefined' || thisSearch.val() == "") {
thisSearch.val(options.defaultValue);
} else if (thisSearch.val() != options.defaultValue) {
thisSearch.css("color", options.focusColor);
}
});
};
})(jQuery);

可以将其直接放入你的js文件中,但是考虑到维护性,笔者建议你将其另存为jQuery.setTip.js,以便多处调用。

之后设置需要启用此功能的输入框

$(document).ready(function () {
$("#newInput").setTip({defaultValue:"世界,你好!"});
});

此时,输入框的提示文字效果就出来了。在线demo

对了,这是jQuery插件,是要先加载jQuery库的哦。

本文最后更新于2017年7月6日,已超过 1 年没有更新,如果文章内容或图片资源失效,请留言反馈,我们会及时处理,谢谢!