问题:针对密码框浏览器默认自动填入密码,并且会弹出保存密码提示
解决办法: <input id="inputText" name="pswView" type="text" class="ps-input" autocomplete="off" placeholder="请输入密码" οnblur="checkPsd()"/>
<input name="psw" id="psw" type="text" style="display: none;" />
inputEle.on("keydown", handlerKeydown);
inputEle.on("compositionstart", function (e) {
e.target.composing = true
});
inputEle.on("compositionend", function (e) {
e.target.composing = false
handlerPassword(e)
// // 输入完成后触发input事件
});
inputEle.on("input", function (e) {
// 避免输入拼音的时候触发该事件
if (e.target.composing) {
return
}
handlerPassword(e)
});
var cursorStart = 0;
var cursorEnd = 0;
function handlerKeydown(e) {
if (e.target.composing) {
return
}
cursorStart = inputEle[0].selectionStart;
cursorEnd = inputEle[0].selectionEnd;
}
function handlerPassword(e) {
var loginForm = document.getElementById("forLogin");
var old_input = loginForm.pswView.value;
var display_input = old_input;
var hide_input = loginForm.psw.value.split("");
if (e.originalEvent.data === ' ') {
loginForm.pswView.value = hide_input.join("").replace(/./g, '*');
return
}
var start = inputEle[0].selectionStart;
var length = Math.abs(cursorEnd - cursorStart);
if (length == 0) {
if (display_input.length < hide_input.length) {
hide_input.splice(start, 1);
} else {
hide_input.splice(cursorEnd, 0, display_input.slice(cursorEnd, start));
}
} else {
if (display_input.length < hide_input.length && cursorStart === start) {
hide_input.splice(start, length);
} else {
hide_input.splice(cursorStart, length, display_input.slice(cursorStart, start));
}
}
var viewPsdValue = "";
var psdValue = "";
for (var i = 0; i < old_input.length; i++) {
viewPsdValue += "*";
}
psdValue = hide_input.join("");
loginForm.pswView.value = viewPsdValue;
loginForm.psw.value = psdValue;
inputEle[0].selectionStart = start;
inputEle[0].selectionEnd = start;
psd = psdValue
}
注意:在输入框中文模式下输入数字,字母会触发两次input事件,所以要结合compositionstart 、input 、compositionend 事件分别判断
在英文状态下,输入只会触发input事件,然后在中文模式下输入会依次触发compositionstart 、input 、compositionend 事件,可以通过compositionstart 事件判断是中文模式还是英文模式,在中文模式下不执行input事件