6 html javascript passwords jquery
我在页面上有密码字段.我想在输入密码之前在屏幕上显示文本"输入密码",但是当用户输入密码时,焦点应该回到密码类型
编辑:我也在使用Jquery,所以任何小的jquery解决方案都可以
Gab*_*oli 11
[包括IE支持的最新修订]
IE9的更新:IE的第9版允许更改text/password类型的输入元素的type属性来回
正如评论中所提到的(并经过验证),前面的例子在IE中不起作用,因为它不允许通过脚本更改类型......这是一个解决方法,它用另一个来回替换元素(代码假设您从文本框开始)
var element = document.getElementById('mysearch');
var text_to_show = 'Enter Password';
element.value = text_to_show; // set the message for the first time
element.onfocus = function(){
if (this.value == text_to_show)
{
var newElement = convertType(this);
newElement.value = '';
setTimeout(function(){document.getElementById(newElement.id).focus()},100);
}
}
element.onblur = function(){
if (this.value == '')
{
var newElement = convertType(this);
newElement.value = text_to_show;
}
}
function convertType(elem)
{
var input = document.createElement('input');
input.id = elem.id;
input.value = elem.value;
input.onfocus = elem.onfocus;
input.onblur = elem.onblur;
input.className = elem.className;
if (elem.type == 'text' )
{ input.type = 'password'; }
else
{ input.type = 'text'; }
elem.parentNode.replaceChild(input, elem);
return input;
}
Run Code Online (Sandbox Code Playgroud)
[更新]
废弃原始答案,我错过了你想保留该字段作为密码的部分(隐藏内容)
修改回答:
var element = document.getElementById('mysearch');
var text_to_show = 'Enter Password';
element.type="text"; // set the type to text for the first time
element.value = text_to_show; // set the message for the first time
element.onfocus = function(){
if (this.value == text_to_show)
{
this.type="password";
this.value = '';
}
}
element.onblur = function(){
if (this.value == '')
{
this.type="text";
this.value = text_to_show;
}
}
Run Code Online (Sandbox Code Playgroud)
[原始答案]
var element = document.getElementById('inputID');
// inputID should be the ID given to the password element
var text_to_show = 'Enter Password'
element.value = text_to_show;
element.onfocus = function(){ if (this.value == text_to_show) this.value = '';}
element.onblur = function(){ if (this.value == '') this.value = text_to_show;}
Run Code Online (Sandbox Code Playgroud)