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

问题描述:

我正在开发我的网站上的登录部分,并希望它使用相同的效果,例如,在Textfield和Password字段为“是”时删除了用户名和密码值关注焦点。我一直在使用普通的JavaScript这与以下几行的一些尝试......登录文本字段和密码字段删除焦点上的文本

function PasswordClick(evt) { 

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

这似乎导致使用Chrome 12.0.742.100在Windows上的问题和概率等网络套件浏览器,但在Firefox正常工作。

有没有人有更好的方式做到这一点?

在此先感谢。

你纠正代码版本:

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.

此代码应该做你想要什么。这部分应该在你的页面的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" /> 

解决方法有很多,一个我觉得最简单的和,并期待最好的是这样的jQuery插件: http://fuelyourcoding.com/scripts/infield/

它增加了一些很不错的效果也。

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

这个SO问题的答案可能会有所帮助,同时也包含一个链接到一个伟大的,但简单的占位符脚本:

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

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