讓IE支持HTML5的新屬性:Placeholder,Autofocus

 藉助jquery,讓IE也支持HTML5新屬性:Placeholder,Autofocus。

 

  1. <!DOCTYPE HTML> 
  2. <html> 
  3. <head> 
  4. <meta charset="UTF-8" /> 
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0"> 
  6. <meta name="description" content=""> 
  7. <meta name="author" content=""> 
  8. <title>test</title> 
  9. <!--[if lt IE 9]> 
  10.     <script src="js/html5shiv-printshiv.js"></script> 
  11. <![endif]--> 
  12. <script src="js/jquery-1.7.2.min.js"></script> 
  13. <script> 
  14.      $(function(){ 
  15.           //autofocus 
  16.           $('[autofocus]:not(:focus)').eq(0).focus(); 
  17.            //placeholder 
  18.           var input = document.createElement("input"); 
  19.           if(('placeholder' in input)==false) { 
  20.                $('[placeholder]').focus(function() { 
  21.                     var i = $(this); 
  22.                     if(i.val() == i.attr('placeholder')) { 
  23.                          i.val('').removeClass('placeholder'); 
  24.                          if(i.hasClass('password')) { 
  25.                               i.removeClass('password'); 
  26.                               this.type='password'
  27.                          }               
  28.                     } 
  29.                }).blur(function() { 
  30.                     var i = $(this);     
  31.                     if(i.val() == '' || i.val() == i.attr('placeholder')) { 
  32.                          if(this.type=='password') { 
  33.                               i.addClass('password'); 
  34.                               this.type='text'
  35.                          } 
  36.                          i.addClass('placeholder').val(i.attr('placeholder')); 
  37.                     } 
  38.                }).blur().parents('form').submit(function() { 
  39.                     $(this).find('[placeholder]').each(function() { 
  40.                          var i = $(this); 
  41.                          if(i.val() == i.attr('placeholder')) 
  42.                               i.val(''); 
  43.                     }) 
  44.                }); 
  45.           } 
  46.      });          
  47. </script> 
  48. <style> 
  49.      .placeholder{ 
  50.           color: #aaa; 
  51.      }      
  52. </style> 
  53. </head> 
  54. <body> 
  55.      <input type="text" placeholder="UserName" autofocus required> 
  56.      <input id="password" type="password" placeholder="Password" required>          
  57. </body> 
  58. </html> 

 

參考:autofocus placeholder


該方案比較簡單,但不是很完美,新方法見新博文:知乎網解決HTML5 Placeholder的方案

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章