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

前端之家收集整理的这篇文章主要介绍了javascript – 如何在密码字段中显示文本前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我在页面上有密码字段.我想在输入密码之前在屏幕上显示文本“输入密码”,但是当用户输入密码时,焦点应该回到密码类型

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

解决方法

[包括IE支持的最新修订]
IE9的更新:IE的第9版允许来回更改text / password类型的输入元素的type属性

正如评论中所提到的(并经过验证),前面的例子在IE中不起作用,因为它不允许通过脚本更改类型……这是一个解决方法,它用另一个来回替换元素(代码假设您从文本框开始)

  1. var element = document.getElementById('mysearch');
  2.  
  3. var text_to_show = 'Enter Password';
  4.  
  5. element.value = text_to_show; // set the message for the first time
  6.  
  7. element.onfocus = function(){
  8. if (this.value == text_to_show)
  9. {
  10. var newElement = convertType(this);
  11. newElement.value = '';
  12. setTimeout(function(){document.getElementById(newElement.id).focus()},100);
  13. }
  14. }
  15. element.onblur = function(){
  16. if (this.value == '')
  17. {
  18. var newElement = convertType(this);
  19. newElement.value = text_to_show;
  20. }
  21. }
  22.  
  23.  
  24. function convertType(elem)
  25. {
  26. var input = document.createElement('input');
  27. input.id = elem.id;
  28. input.value = elem.value;
  29. input.onfocus = elem.onfocus;
  30. input.onblur = elem.onblur;
  31. input.className = elem.className;
  32. if (elem.type == 'text' )
  33. { input.type = 'password'; }
  34. else
  35. { input.type = 'text'; }
  36.  
  37. elem.parentNode.replaceChild(input,elem);
  38. return input;
  39. }

[更新]

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

修改回答:

  1. var element = document.getElementById('mysearch');
  2.  
  3. var text_to_show = 'Enter Password';
  4. element.type="text"; // set the type to text for the first time
  5. element.value = text_to_show; // set the message for the first time
  6. element.onfocus = function(){
  7. if (this.value == text_to_show)
  8. {
  9. this.type="password";
  10. this.value = '';
  11. }
  12. }
  13. element.onblur = function(){
  14. if (this.value == '')
  15. {
  16. this.type="text";
  17. this.value = text_to_show;
  18. }
  19. }

[原始答案]

  1. var element = document.getElementById('inputID');
  2. // inputID should be the ID given to the password element
  3.  
  4. var text_to_show = 'Enter Password'
  5. element.value = text_to_show;
  6. element.onfocus = function(){ if (this.value == text_to_show) this.value = '';}
  7. element.onblur = function(){ if (this.value == '') this.value = text_to_show;}

猜你在找的JavaScript相关文章