placeholder是input標籤的新屬性,在使用的時候有兩個問題:css
一、IE8 下不兼容html
處理思路:jquery
若是瀏覽器不識別placeholder屬性,給input添加類名placeholder,模仿placeholder屬性的樣式,並給input 的value賦值placeholder屬性的值瀏覽器
二、 input的type屬性是password的狀況,用上面的方法處理提示語爲密碼文this
處理思路:spa
新添加一個標籤,模仿placeholder屬性code
直接上代碼:orm
css部分:htm
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部分:blog
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>