前言
本文記錄一下自己手動實現的一個前端常見的簡訊驗證碼輸入元件,從需求到實現逐步優化的過程。
正文
1.需求分析
首先看一下效果圖。
首先頁面載入的時候,輸入框獲取焦點,當用戶輸入一個數字後,焦點自動跳轉到第二個框,當四個框全部輸入後,模擬傳送提交請求,這裡用一個彈框提示,輸出輸入的驗證碼內容。主流程之外的需求: 輸入框內只能輸入數字型別,不能輸入字母,若強制輸入非數字型別按下撤回鍵時候輸入的驗證碼置空並且把當前焦點跳轉至第一個輸入框。
2.完整程式碼實現。
大致思路就是頁面載入的時候,給第一個輸入框新增 autofocus 屬性,讓其自動獲取焦點,然後監聽鍵盤點選事件,當鍵盤按下的時候,判斷當前按鍵是否是數字按鍵,若不是,則當前輸入框置空,焦點還在當前輸入框,若為數字,則判斷前面的輸入框是否有數字存在,若不存在,則把焦點跳轉到前面空的一個輸入框,否則當前輸入框輸入,並且焦點移至下一個輸入框,焦點通過輸入框的一個偽類實現,當輸入長度為為4時候,將每個輸入框數字拼接成字串通過彈框提示。
- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" />
- <meta http-equiv="X-UA-Compatible" content="IE=edge" />
- <meta name="viewport" content="width=device-width, initial-scale=1.0" />
- <title>Document</title>
- <style>
- .check-div {
- width: 400px;
- height: 600px;
- margin: 100px auto;
- border: 1px solid slategrey;
- text-align: center;
- }
- h1 {
- font-size: 24px;
- }
- .input-div {
- margin-top: 100px;
- }
- input {
- margin-left: 5px;
- text-align: center;
- width: 50px;
- height: 50px;
- border: none;
- /* 這裡注意修改預設外邊框屬性,不用border*/
- outline: 1px solid black;
- }
- input:focus {
- outline: 2px solid #3494fe;
- }
- </style>
- </head>
- <body>
- <div class="check-div">
- <h1>請輸入驗證碼</h1>
- <div class="input-div">
- <input
- type="text"
- class="inputItem0"
- data-index="0"
- maxlength="1"
- autofocus
- />
- <input type="text" class="inputItem1" data-index="1" maxlength="1" />
- <input type="text" class="inputItem2" data-index="2" maxlength="1" />
- <input type="text" class="inputItem3" data-index="3" maxlength="1" />
- </div>
- </div>
- <script>
- var inputArr = document.getElementsByTagName("input");
- window.addEventListener("keyup", (e) => {
- let curIndex = e.target.getAttribute("data-index"); //獲取當前輸入的下標
- //如果點選BackSpace刪除 這裡刪除全部
- if (e && e.keyCode == 8) {
- console.log(22222222222);
- for (let j = 0; j <= 3; j++) {
- inputArr[j].value = "";
- inputArr[0].focus();
- }
- return;
- }
- console.log("e.keyCode", e.keyCode);
- //如果輸入的不是數字
- if (!(e.keyCode >= 48 && e.keyCode <= 57)) {
- console.log(1111111111);
- inputArr[curIndex].value = "";
- return false;
- }
- //遍歷陣列的值拼接成驗證碼字串
- var str = "";
- for (let j = 0; j <= 3; j++) {
- console.log(inputArr[j].value);
- str += inputArr[j].value;
- }
- var nextIndex = Number(curIndex) + 1;
- //判斷沒有屬夠四位驗證碼的時候
- if (curIndex < 3 && str.length < 4) {
- for (let i = 0; i <= curIndex; i++) {
- // 判斷之前的是否有空即沒輸入的情況,存在則把焦點調整到前面,並且把輸入的後面給到最前面的一位,否則跳到下一位
- if (!inputArr[i].value) {
- inputArr[curIndex].blur();
- inputArr[i].value = inputArr[curIndex].value;
- var index = i + 1;
- inputArr[index].focus();
- inputArr[curIndex].value = "";
- return;
- } else {
- var nextIndex = Number(curIndex) + 1;
- inputArr[nextIndex].focus();
- }
- }
- } else {
- alert("提交的驗證碼是" + str);
- //輸入了四位驗證碼的時候可以傳送驗證碼請求等等
- }
- });
- </script>
- </body>
- </html>
總結
以上就是本文的全部內容,希望給讀者帶來些許的幫助和進步,方便的話點個關注,小白的成長踩坑之路會持續更新一些工作中常見的問題和技術點。