如何在ie7或更高版本中设置密码字段的占位符

How to set the placeholder for password field in ie7 or higher

本文关键字:设置 密码 字段 占位符 版本 ie7 高版本      更新时间:2023-09-26

我需要在密码字段中显示一些默认文本,如"输入您的密码"。由于我需要支持IE7,占位符属性在这里不是解决方案。我用过对焦和模糊,但在IE浏览器中不起作用。

<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";
    }
}

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

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

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

<input type='password' />

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

请参阅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;
}

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

<script type="text/javascript">$('input[placeholder], textarea[placeholder]').placeholder();</script>