0

好的,我在输入字段中有默认文本作为“密码”,当按下某个键时,我希望它更改为输入类型“密码”。但是当我尝试这样做时,输入不会注册我的第一次按键,但会在输入类型切换后注册所有按键。

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')"
 />
4

3 回答 3

0

HTML5 通过placeholder属性为我们解决了这个问题。无需再次管理事件...请检查以下内容

<input type=password name="pwd" placeholder="Password">
于 2013-05-28T06:06:13.850 回答
0

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

假设你有这样的领域 -

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

方式一:

甚至在 onClick 上,您可以使用 Jquery 替换它,

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

方式二:

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

(注意:这是 jquery 函数可能会在旧 IE 中发出,所以要小心)

方式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">
于 2013-05-28T06:21:03.417 回答
0

举个例子:</p>

<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 上进行了测试。

于 2013-05-28T06:27:13.043 回答