標籤:
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") ||""; inputPrompt.val(tipText); inputPrompt.attr("type", "text"); 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>
效果:
jQuery自訂群組件——輸入框設定預設提示文字