javascript – 如何在密码字段中显示文本

我在页面上有密码字段.我想在输入密码之前在屏幕上显示文本“输入密码”,但是当用户输入密码时,焦点应该回到密码类型

编辑:我也在使用Jquery,所以任何小的jquery解决方案都可以

解决方法

[包括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;
}

[更新]

废弃原始答案,我错过了你想保留该字段作为密码的部分(隐藏内容)

修改回答:

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

[原始答案]

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

相关文章

前言 做过web项目开发的人对layer弹层组件肯定不陌生,作为l...
前言 前端表单校验是过滤无效数据、假数据、有毒数据的第一步...
前言 图片上传是web项目常见的需求,我基于之前的博客的代码...
前言 导出Excel文件这个功能,通常都是在后端实现返回前端一...
前言 众所周知,js是单线程的,从上往下,从左往右依次执行,...
前言 项目开发中,我们可能会碰到这样的需求:select标签,禁...