The old rules ~ When you go to DEMO, you will have fun first: a six-digit character password input device
Then add the source code: six-digit character password inputter
From DEMO, I can see that first, only six characters can be entered, and only numbers are allowed to be entered. After the input of six digits is completed, a callback will be automatically executed (the input result is displayed in DEMO)
1. Let's talk about the principle first
First of all, we need two things: one is a real input box, that is, it is really in focus and obtains the input input input from the user; the other is a set of pseudo input boxes, that is, it does not really obtain the focus, but it only displays the currently entered value (of course, the password is just a small black dot~).
Secondly, we need to be simple and not afraid of it, allowing a set of (6) fake elements to overlap just below the real input box. as follows:
There is actually no margin~, just to see it more clearly.
In addition, we need to set the top-level real input box opcity to 0, so that the one presented to the user is this set of fake input boxes.
However, when the user enters again, he still operates on the real input box. After that, we will fill in the user's input into the forged input box in turn~
Very simple ~
2. Code code
First, the individual DOM is initialized, and the input event is bound.
function init(fun){var that = this;this.callback = fun;that.realInput = container.children[0];that.bogusInput = container.children[1];that.bogusInputArr = that.bogusInput.children;that.maxLength = that.bogusInputArr[0].getAttribute("maxlength");that.realInput.oninput = function(){that.setValue();}that.realInput.onpropertychange = function(){that.setValue();}}Then, when the user input is entered, the user input is entered into the forged input box respectively
function setValue(){this.realInput.value = this.realInput.value.replace(//D/g,"");console.log(this.realInput.value.replace(//D/g,""))var real_str = this.realInput.value;for(var i = 0; i < this.maxLength ; i++){this.bogusInputArr[i].value = real_str[i]?real_str[i]:"";}if(real_str.length >= this.maxLength){this.realInput.value = real_str.substring(0,6); this.callback();}}Finally, we need to get the password~, let’s get a method to get the final value~
function getBoxInputValue(){var realValue = "";for(var i in this.bogusInputArr){if(!this.bogusInputArr[i].value){break;}realValue += this.bogusInputArr[i].value;}return realValue;}The above is the JS implementation of the six-digit character password input function introduced by the editor. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!