jquery模拟input的placeholder属性效果
<!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>
由于比较常用,封装成了插件,按需要调用即可:
如果是密码框的话,就有点问题了,最好的办法是用label标签模拟,判断输入框,如果输入了文字,把lable隐藏就可以了。。。懒得写了。。
可以参考:https://github.com/mathiasbynens/jquery-placeholder DEMO:http://mathiasbynens.be/demo/placeholder
<!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>
浙公网安备 33010602011771号