这完全可以通过各种 JavaScript 选项实现。为了补充 a.stgeorge 发布的关于使用 jquery 的内容,您还可以编写自己的 JS 来完成它。
在此处查看实际操作:http ://www.moditekka.com/pwsample.html
HTML 示例:
<input type="text" name="inpPass" id="inpPass" value="Password"/>
JavaScript 片段(在 IE 中失败,见下文):
var inpPass = document.getElementById("inpPass");
inpPass.onfocus = function() {
if(this.getAttribute("type") == "text") {
this.setAttribute("type", "password");
this.value = "";
}
}
inpPass.onblur = function() {
if(this.value == "") {
this.value = "Password";
this.setAttribute("type", "text");
}
}
编辑:如果有人还在阅读这篇文章,我刚刚意识到我的简洁代码无法在 IE 中运行,这要归功于西雅图的一个聪明决定,即只有在将元素添加到 DOM 后才将“type”属性设为只读。为了适应这一点,我在下面更新了我的 JavaScript 代码:
var inpPass = document.getElementById("inpPass");
inpPass.onfocus = function() {
if(this.getAttribute("type") == "text") {
var newInp = document.createElement('input');
newInp.onfocus = this.onfocus;
newInp.onblur = this.onblur;
newInp.ID = 'inpPass';
newInp.name = 'inpPass';
newInp.setAttribute('type', 'password');
this.parentNode.appendChild(newInp);
this.parentNode.removeChild(this);
newInp.focus();
}
}
inpPass.onblur = function() {
if(this.value == "") {
var newInp = document.createElement('input');
newInp.onfocus = this.onfocus;
newInp.onblur = this.onblur;
newInp.ID = 'inpPass';
newInp.name = 'inpPass';
newInp.setAttribute('type', 'text');
newInp.value = "Password";
this.parentNode.appendChild(newInp);
this.parentNode.removeChild(this);
}
}