登录文本字段和密码字段删除焦点上的文本

Login textfield and password fields remove text on focus

本文关键字:文本 字段 焦点 密码 登录 删除      更新时间:2023-09-26

我正在我的网站上开发登录部分,并希望它使用与twitter相同的效果,即在文本字段和密码字段处于焦点时删除用户名和密码值。我尝试过使用以下几行的纯javascript。。。

function PasswordClick(evt) {
    if ("Password" === this.value) this.value = "";
if(this.getAttribute('type')=='text')
        {
                this.setAttribute('type','password');
        }
        this.focus();
}

在Windows上使用Chrome 12.0.742.100和其他网络工具包浏览器似乎会出现问题,但在Firefox上运行良好。

有人能找到更好的方法吗?

提前谢谢。

您还可以使用与所有现代浏览器兼容的占位符属性,以及为旧浏览器添加相同功能的JQuery占位符脚本。

这个SO问题的答案可能会有所帮助,并且还包含一个指向一个很棒但简单的占位符脚本的链接:

https://stackoverflow.com/questions/5120257/what-is-the-best-html5-placeholder-like-jquery-plugin-out-there

https://github.com/marcgg/Simple-Placeholder

您更正的代码版本:

function PasswordClick(evt) {
    if ("Password" === $(this).val()){$(this).val('');}
    if($(this).attr('type')=='text'){
       $(this).attr({'type':'password'});
    }
        $(this).focus(function(){PasswordClick(evt);});
}

在开始使用jQuery进行编程之前,请阅读一些jQuery文档。

这段代码应该可以随心所欲。这部分应该放在你页面的标题部分:

function init() {
    document.getElementById('password').type = 'text';
}
window.onload = init;
function gotFocus(item) {
    if (item.value == 'Password') {
        item.value = '';
        item.type = 'password';
        item.style.color = '';
    }
}
function lostFocus(item) {
    if(item.value == '') {
        item.value = 'Password';
        item.type = 'text';
        item.style.color = '#C0C0C0';
    }
}

然后你想把密码输入到哪里,你可以把这个HTML:

<input id='password' name='password' type='password' onfocus="gotFocus(this);" onblur="lostFocus(this);" value="Password" style="color:#C0C0C0" />

有很多解决方案,然而,我发现最简单、看起来最好的是这个jQuery插件:http://fuelyourcoding.com/scripts/infield/

它还增加了一些非常好的效果。