zl程序教程

您现在的位置是:首页 >  后端

当前栏目

js动态修改input输入框的type属性(实现方法解析)

JS属性方法 实现 解析 修改 动态 type
2023-06-13 09:15:11 时间

需要实现的效果:一个输入框,当输入框未获得焦点的时候,value值为“密码”;当输入框失去焦点的时候,输入内容显示为”*****”

<inputname=”password”type=”text”id=”showPwd”tabindex=”2″class=”input”value=”密码”/>

我们很直接会想到下面的js

$(“#showPwd”).focus(function(){
$(this).attr(‘type","password");
});

发现并没有实现预期效果,出现uncaughtexceptiontypepropertycan"tbechanged错误,查看jQuery1.42源码1488行

//Wecan"tallowthetypepropertytobechanged(sinceitcausesproblemsinIE)
if(name===“type”&&rtype.test(elem.nodeName)&&elem.parentNode){
jQuery.error(“typepropertycan"tbechanged”);
}

jQuery修改不了用源生的JS呢?

$(“#pwd”).focus(function(){
$(“#pwd”)[0].type=‘password";
$(“#pwd”).val(“”);
});

发现在FF下可以修改并将密码输入框type修改为“password”并将value设置为空,而IE下却提示无法得到type属性,不支持该命令。弹出type看看真的无法得到吗?

$(“#showPwd”).focus(function(){
alert($(“#showPwd”)[0].type);
$(“#showPwd”)[0].type=‘password";
$(“#showPwd”).val(“”);
});

发现弹出text,原来不是无法得到,只是IE下不能修改。因此,我们想到可以先remove然后再生成一个type是password的密码输入框。

下面type为password的输入框

<inputname=”password”type=”password”id=”password”class=”input”style=”display:none;”/>

$(“#showPwd”).focus(function(){
vartext_value=$(this).val();
if(text_value==this.defaultValue){
$(“#showPwd”).hide();
$(“#password”).show().focus();
}
});
$(“#password”).blur(function(){
vartext_value=$(this).val();
if(text_value==“”){
$(“#showPwd”).show();
$(“#password”).hide();
}
});

最终效果:当输入框获得焦点的时,输入的内容显示为“****”;当失去焦点的时,内容为空时显示“密码”。