使用此javascript,占位符适用于IE / Firefox中的文本但不适用于密码框

时间:2011-03-10 10:07:34

标签: javascript

Js档案

//Modified from http://www.beyondstandards.com/archives/input-placeholders/
function activatePlaceholders()
{
    var detect = navigator.userAgent.toLowerCase(); 
    if (detect.indexOf("safari") > 0) return false;
    var inputs = document.getElementsByTagName("input");
    for (var i=0;i<inputs.length;i++)
    {
        if (inputs[i].getAttribute("type") == "text")
        {
            var placeholder = inputs[i].getAttribute("placeholder");
            if (placeholder.length > 0)
            {
                inputs[i].value = placeholder;
                inputs[i].onclick = function()
                {
                    if (this.value == this.getAttribute("placeholder"))
                    {
                        this.value = "";
                    }
                    return false;
                }
                inputs[i].onblur = function()
                {
                    if (this.value.length < 1)
                    {
                        this.value = this.getAttribute("placeholder");
                    }
                }
            }
        }
        else if (inputs[i].getAttribute("type") == "password")
        {
            var placeholder = inputs[i].getAttribute("placeholder");
            if (placeholder.length > 0)
            {
                inputs[i].value = placeholder;
                inputs[i].onclick = function()
                {
                    if (this.value == this.getAttribute("placeholder"))
                    {
                        this.value = "";
                    }
                    return false;
                }
                inputs[i].onblur = function()
                {
                    if (this.value.length < 1)
                    {
                        this.value = this.getAttribute("placeholder");
                    }
                }
            }
        }
    }
}
window.onload = function()
{
    activatePlaceholders();
}

Html部分

<form name="input" action="login.php" method="post">
        <table width="*" border="0">
        <tr>
        <td align="left"><input type="text" name="username" placeholder="Username" />&nbsp;<input type="password" name="pass" placeholder="Password" /><input type="submit" value="Login" /></td>
        </tr>
        <tr>
        <td colspan="2" align="right">Stay logged in:&nbsp;<input type="checkbox" name="remember" value="1">&nbsp;&nbsp;Sign Up | Forgot Password&nbsp;&nbsp;&nbsp;</td>
        </tr>
        </table>
        </form>

这适用于输入框。不适用于密码框。它希望在密码上标出占位符文本。我希望用户密码可以启动,但不是占位符。不知道如何解决这个问题,因此它适用于IE和Firefox。

1 个答案:

答案 0 :(得分:2)

var passwords = document.getElementsByTagName("password");

应该是:

var passwords = document.getElementsByTagName("input");

因为<input type="password">不是<password...>。但是,在这种情况下,我认为这不会对您有所帮助,因为当您设置密码的值时,您将看到的只是黑点/星号。