placeholder是input标签的新属性,在使用的时候有两个问题:
1、IE8 下不兼容
处理思路:
如果浏览器不识别placeholder属性,给input添加类名placeholder,模仿placeholder属性的样式,并给input 的value赋值placeholder属性的值
2、 input的type属性是password的情况,用上面的方法处理提示语为密码文
处理思路:
新添加一个标签,模仿placeholder属性

直接上代码:
css部分:
1 .input-item {
2 position: relative;
3 margin: 10px;
4 }
5 .pwd-place {
6 position: absolute;
7 top: 0;
8 left: 72px;
9 width: 100%;
10 height: 100%;
11 font-size: 12px;
12 }
html部分:
1 <form action="#"> 2 <div class="input-item"> 3 <label for="userName">用户名:</label> 4 <input class="username" id="userName" type="text" placeholder="请输入用户名"> 5 </div> 6 <div class="input-item"> 7 <label for="pwd">密码:</label> 8 <input class=" password" id="pwd" type="password" placeholder="请输入密码"> 9 <span class="pwd-place"></span> 10 </div> 11 12 </form>
js部分:
1 <script src="jquery-1.11.3.js"></script>
2 <script>
3 function placeholder(el){
4
5 function isPlaceholer(){
6 var input = document.createElement("input");
7 return "placeholder" in input;
8 }
9
10 var $el = $(el);
11 if( isPlaceholer()==false && !('placeholder' in document.createElement('input')) ){
12
13 $('input[placeholder],textarea[placeholder]').each(function(){
14 var that = $(this),
15 text= that.attr('placeholder');
16 if(that.val()===""){
17 if(that.attr("type") == "password"){
18 $el.html("请输入密码");
19 }else {
20 that.val(text).addClass('placeholder');
21 }
22 }
23 that.focus(function(){
24 if($el.html() == text){
25 $el.html("");
26 }
27 if(that.val()===text) {
28 that.val("").removeClass('placeholder');
29
30 }
31 })
32 .blur(function(){
33 if(that.val()==="") {
34 if (that.attr("type") == "password") {
35 $el.html("请输入密码");
36
37 }else {
38 that.val(text).addClass('placeholder');
39 }
40 }
41 })
42 .closest('form').submit(function(){
43 if(that.val() === text){
44 that.val('');
45 }
46 });
47 });
48 }
49 }
50 $(document).ready(function() {
51 placeholder(".pwd-place")
52 });
53 </script>
来源:https://www.cnblogs.com/candice-cc/p/5946100.html