您的位置:首页 > Web前端 > JavaScript

JS 动态修改 input 的 type 属性

2012-09-26 10:05 656 查看
很久没来部落格了,杂草丛生广告横行啊!工作比以前轻松很多人却越来越懒了…… 最近做一个登陆框,当鼠标焦点放在两个输入框上面的时候将输入框置空,简单说就是清除输入框的默认值,如图





这里写了一个jQuery对象方法的插件

(function($) {
jQuery.fn.extend({
“clearDefault”:function(className){
$(this).focus(function(){
if (className) {
$(this).addClass(className);
}
if($(this).val() ==this.defaultValue){
$(this).val(“”);
}
}).blur(function(){
if (className) {
$(this).removeClass(className);
}
if ($(this).val() == ”) {
$(this).val(this.defaultValue);
}
});
}
});
})(jQuery);

调用: $(“#uname”); 可选参数class为获取焦点时input的class,但是清除密码的时候出了一个问题,用户输入的密码应该是 ”*****” ,这里需要将input 的type 属性由 text 换成 password ,如果用户没有输入密码,鼠标失去焦点的时候 type 换回 text ,value 值为 “密码”。

$(“#pswd”).focus(function(){
$(this).attr(‘type’,'password’);

发现并没有实现预期效果,出现 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” );

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

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

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

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

发现弹出text ,原来不是无法得到,只是IE下不能修改。 各种 google 后发现input的type属性只能在初始的时候设定却不能修改(IE不能,FF可以,个人认为,不知道是否准确,如有不对请大牛指教)。 这样我是否可以先remove然后再生成一个type是password的密码输入框呢?

$(“#pwd”).focus(function(){
$(“#pwd”).remove();
$(“body”).append(‘<input id=“pwd” name=“pwd” type=“password” />’);

$(“#pwd”).focus(); // 焦点转移

});

可以实现,但是输入为空鼠标失去焦点再返回到起始状态的时候不怎么好写,节点生成删除为什么不用两个密码框来显示隐藏呢?

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

<input id=“pwd” class=“txt” name=“password” type=“password” />

var showPwd = $(“#showPwd”), pwd = $(“#pwd”);
showPwd.focus(function(){
pwd.show().focus();
showPwd.hide();
});
pwd.blur(function(){
if(pwd.val()==“”) {
showPwd.show();
pwd.hide();
}
});





完美解决。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: