使用场景

需要实现的效果:一个输入框,当输入框未获得焦点的时候,显示为 “请输入密码”;
当输入内容并失去焦点的时候,输入内容显示为” * ”,如果没有输入仍然显示“请输入密码”,通常做法是:

  1. 使用text,隐藏域中,然后配合onkeypress、onkeyup、focus、blur等事件基本可以达到要求,此种方法比较麻烦;
  2. 用text和password两个输入框,模拟

实现方法

在这里主要讲讲如何用第二种方式实现。

html代码

<input type="password" id="input_password" value='' style="display:none;color:#444;"/>
<input type="text" id="showPwd" value="请输入密码" style="color:#c0c0c0"/>

js代码

$("#showPwd").focus(function() {
    var text_value = $(this).val();
    if(text_value == "请输入密码") {
          $("#showPwd").hide();
        $("#input_password").show().focus();
       }
});
$("#input_password").blur(function() {
       var text_value = $(this).val();
    if(text_value == "") {
        $("#showPwd").show();
        $("#input_password").hide();
    }
});

至此完美解决,所有浏览器都可以使用。

扩展内容

也许很多人一开始想到的是用jquery的attr修改type属性值,但是测试发现在IE上会出错,如下:
uncaught exception type property can't be changed
查看到jQuery 1.42源码:

1
2
3
4
// We can't allow the type property to be changed (since it causes problems in IE)
if(name === "type" && rtype.test(elem.nodeName) && elem.parentNode){
jQuery.error("type property can't be changed");
};

主要还是“万能”的IE浏览器禁止修改input的type属性造成的。

本文地址: http://wsdever.github.io/2015/03/24/20150324/