键入时将密码设置为变量

时间:2018-11-28 17:58:19

标签: javascript jquery html

试图避免浏览器出现任何有关autocompletepassword suggestion等的内容。

并同时保留show/hide letters功能。

这个想法是将password保留为变量,而不考虑show/hide的状态。

在下面的代码中,问题是用户是否按BackspaceDelete键。在这种情况下,整个概念就会崩溃。

有帮助吗?

var pass = "";

$('#inpass').on('input', function(){
	if(!$('#checka').is(':checked')){
		let a = $(this).val();
		let b = a.substr(-1);
		pass += b;
		let c = a.replace(/.$/, '*');
		$(this).val(c);
		console.log(pass);
	}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type='text' id='inpass' maxlength='25' placeholder='password' title='password' autocomplete='off'>
<br><br>
<input type='checkbox' id='checka'>
<label for='checka' id='labela'>show letters</label>

1 个答案:

答案 0 :(得分:3)

Added检查是删除还是添加

var pass = "";
String.prototype.replaceAt = function (index, replacement) {
    return this.substr(0, index) + replacement + this.substr(index + replacement.length);
}

function setCaretPosition(ctrl, pos) {
    if (ctrl.setSelectionRange) {
        ctrl.focus();
        ctrl.setSelectionRange(pos, pos);
    } else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

$('#inpass').on('input', function(){
	var el = document.getElementById('inpass');
    let caretStart = el.selectionStart;

    let a = $(this).val();
    var deleteLength = pass.length - a.length;
    var addLength = deleteLength * -1;
    let b = a.substr(caretStart - addLength, addLength);
    if (deleteLength > 0) {
        pass = pass.substr(0, caretStart) + pass.substr(caretStart + deleteLength, pass.length - 1);
    } else {
        if (caretStart < a.length) {
            pass = pass.substr(0, caretStart - addLength) + b + pass.substr(caretStart - addLength);
        } else {
            pass += b;
        }
    }
    if (!$('#checka').is(':checked')) {
        if (a != "" && addLength > 0) {
            let c = a.replaceAt(caretStart - addLength, '*'.repeat(addLength));
            $(this).val(c);
        }

    }
    setCaretPosition(el, caretStart);
    console.log(pass);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

<input type='text' id='inpass' maxlength='25' placeholder='password' title='password' autocomplete='off'>
<br><br>
<input type='checkbox' id='checka'>
<label for='checka' id='labela'>show letters</label>