实现password框中显示文字提示的方式

其实实际上实现中并不能让password中显示文字提示,但是我们在工作中有这样的需求,当没输入东西的时候,框内有提示输入密码,但是当输入东西的时候又显示的是*号,那么是如何实现的呢?其实原理很简单,就是放两个文本框,样式以及定位都是一样的。先将type为password的隐藏,只显示type为text的伪密码框,value设置提示内容例如请输入密码。然后当input触发的时候,type为text的input隐藏,让type为password的input显示出来。然后当检测password的value为空的时候,再将type为password隐藏,type为text的显示。啥话也不说了,上代码。(ps:额外添加了重置功能)

先上html部分

<table class="login_table">
      <tr>
        <td>账号</td>
        <td><input type="text" value="请输入您的账号" class="admin" /></td>
      </tr>
      <tr>
        <td>密码</td>
        <td>
            <input type="text" value="请输入您的密码"id="login_showPwd" />
            <input type="password"id="login_password" style="display: none"/>
        </td>
      </tr>
      <tr>
        <td>
         <input type="button" value="登录" />
         <input type="button" value="重置" id ="btn_res"/>
        </td>
      </tr>
   </table>

然后上js部分

//账号部分
$(function(){
      $(".admin").focus(function(){
        if($(this).val() == "请输入您的账号"){
        $(this).val("");
         }
     });
     $(".admin").blur(function(){
         if($(this).val() == ""){
         $(this).val("请输入您的账号");
         }
 });
// 密码部分
$('#login_showPwd').focus(function(){
    var text_value=$(this).val();
    if(text_value == this.defaultValue){
        $('#login_showPwd').hide();
        $('#login_password').show().focus();
    }
});
     $('#login_password').blur(function(){
         var text_value = $(this).val();
         if(text_value==""){
            $('#login_showPwd').show();
             $('#login_password').hide();
         }
     });
//重置部分
     $('#btn_res').click(function(){
         $('.admin').val("请输入您的账号");
         $('#login_password').hide().val("");
         $("#login_showPwd").show();
     });
});

 PS:有朋友说可以使用给input填入placeholder="请输入您的密码"这个属性,这个属性是h5新提供的,如果不要求兼容ie8和9,那么是可以直接使用这个标签不用写js的。如果需要兼容ie,那么可能得麻烦一些用上面的方法。但是ie8测了下貌似上面的方法也无效不兼容。

原文地址:https://www.cnblogs.com/hanyining/p/5531861.html