繁体   English   中英

如何在没有按键延迟的情况下将输入类型更改为密码

[英]How to change input type to password without key press delay

好的,我在输入字段中有默认文本作为“ password”,当我按下一个键时,我希望它更改为输入类型“ password”。 但是,当我尝试执行此操作时,输入不会注册我的第一个按键,但是会在输入类型切换之后注册所有的按键。

function inputField(focus, inputValue, inputID){
// change inputID variable into pointer to the actual ID
var iD = document.getElementById(inputID);

// check if input has focus and handle default value changes, password field type changes, and font color changes.
if (focus == "on"){

    if(iD.value == inputValue){
        iD.setSelectionRange(0, 0);
        iD.style.color = "#b2b2b2";
    }
    iD.onkeypress = function(){
        if(iD.value == "password" || iD.value == "retype password"){
            iD.type = "password";
        }
        if (iD.value != "" && iD.value == inputValue){
                iD.value = "";
                iD.style.color = "#000000";
        }
    }
}else if(focus == "off"){
    if (iD.value == ""){
        if(iD.type == "password"){
            iD.type = "text";
        }
        iD.style.color = "#787878";
        iD.value = inputValue;
    }else if(iD.value == inputValue){
        iD.style.color = "#787878"
    }
}
}

<input
 id = "registerPassword"
 class = "loginSectionInput"
     type = "text"
 name = "rPassword"
 value = "password"
 onfocus = "inputField('on', 'password', this.id)"
 onblur = "inputField('off', 'password', this.id)"
 onchange = "formCheck('registerPassword')"
 />

HTML5通过占位符属性为我们解决了这个问题。 无需再次管理活动...请检查以下内容

<input type=password name="pwd" placeholder="Password">

您可以用不同的方式来做,这里列出了其中的一些! 希望我能帮助你

假设您有喜欢的领域-

<input type="text" id="mypswfield" name="mypswfield" />

方法1:

您甚至可以在o​​nClick上使用Jquery替换它,

$('#mypswfield').replaceWith('<input type="password" id="mypswfield" />')

方式2:

$("[name=fieldname]").attr("type", "password");

(注意:这是旧的IE中可能会发出的jquery函数,请谨慎操作)

方法3:创建功能

function txtField()
{
     if(document.getElementById('mypswfield').value=='')
     {
        document.getElementById('mypswfield').type='text';
        document.getElementById('mypswfield').value='Password';

     }

}
function txtPawd()
{
    document.getElementById('mypswfield').type='password'; 
    document.getElementById('mypswfield').value='';

}

的HTML

<input id="mypswfield" onclick="txtField();" onblur="txtPawd();" name="mypswfield" type="text" value="Password">

举个例子:

<html><head><script>function swithch(){
  alert("myText is ");
    var myText=document.getElementById("myId");
    alert("myText is "+myText);
    alert("myText is type "+myText.type);
    alert("myText is  value "+myText.value);
    myText.type='text';
    myText.value='56789';
  }</script></head><body>
 TT <input type="password" name="myText" id="myId" value="123456"/> <input type="button" name="switch" value="swithch" onclick="swithch()">

此代码已在google chrome中经过测试。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM