使用HTML CSS和JavaScript创建OTP输入框
在本文章中,我们将探讨如何构建一个常用于许多网站的OTP(一次性密码)输入框。这个交互式和引人入胜的UI元素允许用户方便高效地输入他们的OTP。我们将逐步介绍使用HTML,CSS和JavaScript创建这个功能的步骤。
设置项目
首先,通过创建一个名为“OTP输入”的文件夹并将其打开到我们喜欢的代码编辑器中,来设置项目结构。在这个文件夹中,创建三个文件: index.html , style.css 和 script.js 。在 index.html 文件中使用HTML5代码,并设置一个实时服务器以便更方便地开发和测试。
创建OTP输入框UI
OTP输入框由一个容器、一组输入框和一个带下划线的设计组成。创建一个容器,并给它分配一个类名为“container”。在容器内部,添加一个绿色的盒子,用于容纳各个输入框。每个输入框都将有一个类名为“input”,类型为“text”,并设置输入模式为“numeric”,以确保在移动设备上显示数字键盘。创建四个输入框,其长度将限制为一个字符。
HTML
<!-- index.html -->
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width,
initial-scale=1.0" />
<meta http-equiv="X-UA-Compatible" content="ie=edge" />
<title>OTP Input</title>
<link rel="stylesheet" href="style.css" />
</head>
<body>
<div class="container">
<div id="inputs" class="inputs">
<input class="input" type="text"
inputmode="numeric" maxlength="1" />
<input class="input" type="text"
inputmode="numeric" maxlength="1" />
<input class="input" type="text"
inputmode="numeric" maxlength="1" />
<input class="input" type="text"
inputmode="numeric" maxlength="1" />
</div>
</div>
<script src="script.js"></script>
</body>
</html>
设置OTP输入框的样式
使用flexbox属性将OTP输入框居中对齐。在CSS中选择input类,并应用特定的样式,例如宽度、边框、边距、文本对齐和字体大小。此外,当输入框获得焦点时,可以通过将边框颜色改为橙色来修改其外观。
CSS
/* style.css */
.container {
display: flex;
justify-content: center;
align-items: center;
min-height: 100vh;
}
.input {
width: 40px;
border: none;
border-bottom: 3px solid rgba(0, 0, 0, 0.5);
margin: 0 10px;
text-align: center;
font-size: 36px;
cursor: not-allowed;
pointer-events: none;
}
.input:focus {
border-bottom: 3px solid orange;
outline: none;
}
.input:nth-child(1) {
cursor: pointer;
pointer-events: all;
}
实现JavaScript功能
为了启用输入框的导航和交互,我们添加JavaScript代码。指定橙色的框并添加事件监听器来处理输入事件。在事件回调中,获取输入的值并检查是否为数字。如果不是数字,则删除该值并返回。接下来,使用“nextElementSibling”属性识别下一个输入框,并将焦点移动到该框。此外,添加一个事件监听器用于处理删除操作的按键事件。当按下退格键或删除键时,将焦点移动到上一个输入框,并从当前输入框中删除值。
防止非活动框中的输入:
为了防止非活动输入框中的输入,添加CSS样式。默认情况下,所有输入框都将具有“cursor: not allowed”和“pointer-events: none”的属性。但是,为第一个输入框覆盖这些样式,允许其接收输入。
Javascript
// script.js
const inputs = document.getElementById("inputs");
inputs.addEventListener("input", function (e) {
const target = e.target;
const val = target.value;
if (isNaN(val)) {
target.value = "";
return;
}
if (val != "") {
const next = target.nextElementSibling;
if (next) {
next.focus();
}
}
});
inputs.addEventListener("keyup", function (e) {
const target = e.target;
const key = e.key.toLowerCase();
if (key == "backspace" || key == "delete") {
target.value = "";
const prev = target.previousElementSibling;
if (prev) {
prev.focus();
}
return;
}
});
输出: