-3

我需要在密码字段中显示一些默认文本,例如“输入您的密码”。由于我需要支持 IE7,所以 placeholder 属性在这里没有解决方案。我使用了 onfocus 和 blur 但它在 Internet Explorer 中不起作用。

<input type="text" value="Enter the password" id="fieldPassword" onfocus="showPass()" onblur="hidePass()"/>
function showPass()
{
    var pass = document.getElementById('fieldPassword').value;
    if((pass=="Enter the password")||pass=="")
    {
        document.getElementById('fieldPassword').type="password";
        document.getElementById('fieldPassword').value="";   
    }
    else
    {
    }
}

function hidePass()
{
    var pass = document.getElementById('fieldPassword').value;
    if(pass=="")
    {
        document.getElementById('fieldPassword').type="text";
        document.getElementById('fieldPassword').value="Enter the password";
    }
}
4

3 回答 3

4

为了实现这一点,您必须使用

<input type='text' value='Enter your password' />

在单击/聚焦时,您将输入元素的类型更改为

<input type='password' />

如果值没有变化,则在模糊时将其更改回文本类型。您也可以使用显示/隐藏的 2 个不同输入来实现此目的,但在这种情况下,您必须触发对新可见元素的关注,并且您不能对两者使用相同的 id。

于 2012-09-02T15:45:00.513 回答
0

http://jsfiddle.net/9GTcL/2/

HTML:

<div class="placeholder">
    <input type="password" id="pswdInput" />
    <input type="text" value="Enter password..." id="textInput" />
</div>

JavaScript:

var text=document.getElementById('textInput'),
    pswd=document.getElementById('pswdInput');
text.onfocus=pswd.onfocus=function(){
    text.style.display='none';
    pswd.focus();
}
pswd.onblur=function(){
    if(pswd.value==''){
        text.style.display='block';
    }
}

CSS:

.placeholder{
    position:relative;
}
.placeholder>#textInput{
    position:absolute;
    top:0;
    left:0;
}
.placeholder>input{
    width:140px;
}
于 2012-09-02T18:10:59.317 回答
-1

这是我用来在 IE 中使用占位符的 js 文件,只需下载它并将其链接到页面的标题中,然后在结束正文标记之前添加这段代码:

<script type="text/javascript">$('input[placeholder], textarea[placeholder]').placeholder();</script>
于 2012-09-02T16:28:11.890 回答