解决方法
[包括IE支持的最新修订]
IE9的更新:IE的第9版允许来回更改text / password类型的输入元素的type属性
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;}