JQ无法修改input的type属性的替代解决方法

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

方法一:使用text,隐藏域中,然后配合onkeypress、onkeyup、focus、blur等事件基本可以达到要求,此种方法比较麻烦;

方法二:用text和password一起  

html: 

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

js:

 1 $("#showPwd").focus(function() {
 2     var text_value = $(this).val();
 3     if (text_value == "请输入密码") {
 4           $("#showPwd").hide();
 5         $("#input_password").show().focus();
 6     }
 7 });
 8 $("#input_password").blur(function() {
 9     var text_value = $(this).val();
10     if (text_value == "") {
11         $("#showPwd").show();
12         $("#input_password").hide();
13     }
14 });

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

扩展内容:

本来想使用JQ的attr修改type属性值,但是发现在IE上会出错,如下:uncaught exception type property can't be changed

查看jQuery 1.42源码 1488 行

// 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不支持修改type属性。

原文地址:https://www.cnblogs.com/wsun/p/5630000.html