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

时间:2011-06-26 15:13:51

标签: javascript jquery html css

我正在我的网站上开发登录部分,并希望它在使用与文本字段和密码字段聚焦时删除用户名和密码值相同的效果(如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上运行正常。

有没有人有更好的方法呢?

提前致谢。

4 个答案:

答案 0 :(得分:2)

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

此SO问题的答案可能会有所帮助,并且还包含指向优秀而简单的占位符脚本的链接:

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

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

答案 1 :(得分:0)

您更正后的代码版本:

function PasswordClick(evt) {

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

Please, read some jQuery documentation before start programming with it.

答案 2 :(得分:0)

此代码应该按照您的意愿执行。这部分应该放在页面的HEAD部分:

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" />

答案 3 :(得分:0)

有许多解决方案,但是,我发现最容易的,并且看起来最好的是这个jQuery插件: http://fuelyourcoding.com/scripts/infield/

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