$.fn.placeHolder = function(){ $(this).each(function(i, el) { var self = $(el); if ($.browser.msie && !("placeholder" in $("<input/>")[0])) { if(self.attr("data-placeHolder")||!self.attr("placeholder")){ return; } self.attr("data-placeHolder",true); var that = $("<div/>"); var parent = self.parent(); if(parent.css("position")!=="absolute"&&parent.css("position")!=="fixed"){ parent.css("position", "relative"); } that.css({ "left": self.offset().left - parent.offset().left + parseInt(self.css("borderLeftWidth")), "top": self.offset().top - parent.offset().top + parseInt(self.css("borderTopWidth")), "width":self.width(), "height":self.height(), "lineHeight":self.css("lineHeight"), "fontSize":self.css("fontSize"), "paddingLeft":self.css("paddingLeft"), "paddingTop":self.css("paddingTop"), "textIndent":self.css("textIndent"), "position":"absolute", "color":"#666669", "outline":"none!important", "border":"none!important", "backgroundColor":"transparent", "cursor": "text" }); that.html(self.attr("placeholder")); parent.append(that); that.on("click", function() { self[0].focus(); }); function showPlaceholder() { if (self.val() === "") { that.show() } else { that.hide(); } } self.on("input propertychange", showPlaceholder); showPlaceholder(); } }); }; $(function() { $("[placeholder]").placeHolder(); });
改变placeholder的默认颜色代码如下:
::-moz-placeholder{color:red;} //ff ::-webkit-input-placeholder{color:red;} //chrome,safari :-ms-input-placeholder{color:red;} //ie10
Placeholder插件在支持自带placeholder的浏览器原样显示不处理,低版本在同级创建div。(记得引入jQuery)