<!doctype html> <html> <head> <meta charset="UTF-8"> <title>jquery模拟input的placeholder属性效果</title> <script src="script/jquery-1.10.2.js"></script> <script> $(function(){ if (! ("placeholder" in document.createElement("input"))) { $("input[placeholder]").each(function(){ var self = $(this); var color = self.css("color"); var place = self.attr("placeholder"); self.val(place); self.css("color", "#bbb"); self.on({ focus: function(){ if(self.val() == place){ self.val(""); } self.css("color", color); }, blur: function(){ if(self.val() == ""){ self.val(place); self.css("color", "#bbb"); } } }); }); } }); </script> </head> <body> <p><input type="text" name="" placeholder="请输入搜索内容"/></p> <p><input type="text" name="" placeholder="哈哈。。"/></p> </body> </html>
因为比较经常使用,封装成了插件,按须要调用便可:css
若是是密码框的话,就有点问题了,最好的办法是用label标签模拟,判断输入框,若是输入了文字,把lable隐藏就能够了。。。懒得写了。。html
能够参考:https://github.com/mathiasbynens/jquery-placeholder DEMO:http://mathiasbynens.be/demo/placeholderjquery
<!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Document</title> <style> input {height:20px;line-height:20px;color:#333;border:1px solid #999;} </style> </head> <body> <input type="text" name="" id="search" placeholder="请输入内容。。。"> <input type="text" name="" id="user" placeholder="dfdsfd"> <br/> <textarea name="" id="" cols="30" rows="10" placeholder="请输入留言内容。。。"></textarea> <script src="http://code.jquery.com/jquery-1.10.2.min.js"></script> <script> ;(function($){ $.fn.extend({ placeholder: function() { if ("placeholder" in document.createElement("input")) return; $(this).each(function() { var self = $(this); var place = self.attr("placeholder"); var color = self.css("color"); self.val(place).css("color", "#aaa"); self.on({ focus: function() { if (self.val() == place) { self.val(""); } self.css("color", color); }, blur: function() { if (self.val() == "") { self.val(place).css("color", "#aaa"); } } }); }); } }); })(jQuery); $(function() { //$("#search").placeholder(); $("input, textarea").placeholder(); }) </script> </body> </html>