JS 将输入的值转换为* 表单 type 是 text
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<input id="password" type="text" placeholder="密码" password="" >
</body>
<script>
window.onload = function () {
document.getElementById("password").addEventListener('input', function () {
var _this = this;
var newPassword = _this.value;
var oldPassword = _this.getAttribute("password");
var truePassword = "";
var p = _this.selectionEnd;//光标结束时的位置
console.log("光标结束时的位置",p)
for(var i=0; i<newPassword.length; i++){
var c = newPassword.charAt(i);
if(i<p && c!='●'){
truePassword += c;
}else if(i<p && c=='●'){
truePassword += oldPassword.charAt(i);
}else {
truePassword += oldPassword.substr(oldPassword.length-newPassword.length+p,newPassword.length-p);
break;
}
}
newPassword = truePassword.replace(/\S/g, '●');
_this.setAttribute('password', truePassword);
_this.value = newPassword;
// 解决在win8中光标总是到input框的最后
_this.selectionEnd = p;
_this.selectionStart = p;
//console.log(truePassword);
},false);
}
</script>
</html>