jQuery自定义组件——输入框设置默认提示文字
if (window.jQuery || window.Zepto) { /** * 设置输入框提示信息 * @param options * @author rubekid */ var setInputTipValue = window.setInputTipValue = function(target, options){ options = options ||{}; var _self = target.get(0); if(_self._initTip){ return false; } target.show(); var color = options.color||"#999999"; var inputPrompt = target.clone(); var name = target.attr("name"); var tipText = options.tipText || target.attr("data-tip") ||""; if(inputPrompt.is(":input") && inputPrompt.attr("type") != "text"){ inputPrompt = $('<input type="text" />'); } inputPrompt.val(tipText); inputPrompt.removeAttr("id"); inputPrompt.removeAttr("name"); inputPrompt.removeAttr("maxlength"); inputPrompt.removeAttr("data-tip"); inputPrompt.attr("class", target.attr("class")); inputPrompt.attr("readonly", true); inputPrompt.css({"color":color}); _self._initTip = true;//设置标示,防止重复绑定 var _event = "focus"; if('ontouchstart' in window){ //手机浏览器聚焦无法弹出键盘处理 inputPrompt.attr("disabled", "disabled"); _event = "touchstart"; } var init = function(){ if($.trim(target.val())==""){ target.val(""); target.after(inputPrompt); target.hide(); inputPrompt.show(); inputPrompt.bind(_event,function(){ setTimeout(function(){ target.focus(); }); }); } }; target.bind({ blur: function(){ init(); }, focus:function(){ inputPrompt.detach(); $(this).show(); }, _reset:function(){ if($.trim(target.val())==""){ init(); } else{ target.show(); if(inputPrompt){ inputPrompt.hide(); inputPrompt.remove(); } } } }); init(); }; /** * jQuery 自定义插件 */ (function ($) { 'use strict'; /** * 设置输入灰色提示值 * @author rubekid */ $.fn.setInputTip = function(options){ return this.each(function(){ var settings = $.extend({}, options||{}); setInputTipValue($(this), settings); }); }; })(window.jQuery || window.Zepto); }
页面调用demo:
<input type="text" data-tip="请输入要名称进行查询" id="keyword" name="keyword" /> <script type="text/javascript"> $(function(){ $("#keyword").setInputTip(); }); </script>
效果: