之前公司有这样的效果,placeholder和之前那种js模拟value的有一些区别,之前的那种都是在input文本框得到焦点的时候就消失了,而 html5引入的placeholder则不是,当得到焦点的时候是不消失的只有在你输入内容的时候才消失,固然由于一些低级浏览器不支持这个属性,固然 表明是IE浏览器,貌似IE9还不支持呢,其是模拟的思路也是比较简单的,就是在不支持的浏览器上建立一个label来模拟placeholder,具体 的你们能够看看源代码,由于说很苍白,看了代码就都明白了,固然难点多是在于两个方法,一个是oninut和onpropertychange,固然你 能够开定时器来获取,固然那样我认为性能太差,可是兼容性最好~好了不说直接上代码了~ css
;(function ($) { $.fn.placeholder = function (options) { var defaults = { pColor: "#333", pActive: "#999", pFont: "14px", activeBorder: "#080", posL: 8, zIndex: "99" }, opts = $.extend(defaults, options); // return this.each(function () { if ("placeholder" in document.createElement("input")) return; $(this).parent().css("position", "relative"); var isIE = $.browser.msie, version = $.browser.version; //不支持placeholder的浏览器 var $this = $(this), msg = $this.attr("placeholder"), iH = $this.outerHeight(), iW = $this.outerWidth(), iX = $this.position().left, iY = $this.position().top, oInput = $("<label>", { "class": "test", "text": msg, "css": { "position": "absolute", "left": iX + "px", "top": iY + "px", "width": iW - opts.posL + "px", "padding-left": opts.posL + "px", "height": iH + "px", "line-height": iH + "px", "color": opts.pColor, "font-size": opts.pFont, "z-index": opts.zIndex, "cursor": "text" } }).insertBefore($this); //初始状态就有内容 var value = $this.val(); if (value.length > 0) { oInput.hide(); }; // $this.on("focus", function () { var value = $(this).val(); if (value.length > 0) { oInput.hide(); } oInput.css("color", opts.pActive); // if(isIE && version < 9){ var myEvent = "propertychange"; }else{ var myEvent = "input"; } $(this).on(myEvent, function () { var value = $(this).val(); if (value.length == 0) { oInput.show(); } else { oInput.hide(); } }); }).on("blur", function () { var value = $(this).val(); if (value.length == 0) { oInput.css("color", opts.pColor).show(); } }); // oInput.on("click", function () { $this.trigger("focus"); $(this).css("color", opts.pActive) }); // $this.filter(":focus").trigger("focus"); }); } })(jQuery);