JavaScript实现高仿支付宝密码输入框

作者:代码拾荒时间:2026-10-29 19:26:04浏览:236

本文介绍如何使用JavaScript和CSS模拟支付宝风格的密码输入框。通过控制input焦点移动、监听键盘事件及移动端数字键盘唤起,实现输入一位自动跳转下一位及退格回退效果。

JavaScript实现高仿支付宝密码输入框

当前移动支付场景日益普及,随着H5页面开发技术的成熟,许多原本依赖客户端的功能已迁移至浏览器环境,支付环节也不例外。对于这种样式的输入框,用户应当十分熟悉。

JavaScript实现高仿支付宝密码输入框

接下来将使用JavaScript代码复现该效果。首先明确整体思路:确定密码位数,本例设定为5位,使用一个div容器包裹5个input元素。

为这5个input设置display: inline-block属性,并利用HTML注释<!- ->消除元素间的margin间距,HTML结构如下所示。


<div class="input"> 
<input type="tel" placeholder="随" maxlength=""><!- 
-><input type="tel" placeholder="机" maxlength=""><!- 
-><input type="tel" placeholder="" maxlength=""><!- 
-><input type="tel" placeholder="位" maxlength=""><!- 
-><input type="tel" placeholder="数" maxlength=""> 
</div> 

代码中需限制最大输入位数,以符合实际体验。同时,为确保移动端能唤起数字键盘,需将input的type属性设置为tel。随后是CSS样式部分,此处仅展示部分关键代码,高仿程度主要取决于CSS细节。


input { 
display: inline-block; 
&:last-child { 
border-right: px solid #; 
} 
input { 
border-top: px solid #; 
border-bottom: px solid #; 
border-left: px solid #; 
width: px; 
height: px; 
outline:none; 
font-family: inherit; 
font-size: px; 
font-weight: inherit; 
text-align: center; 
line-height: px; 
color: #ccc; 
background: rgba(,,,); 
} 
}

接下来是最为核心的JavaScript逻辑部分。


/** 
* 模拟支付宝的密码输入形式 
*/ 
(function (window, document) { 
var active = , 
inputBtn = document.querySelectorAll('input'); 
for (var i = ; i < inputBtn.length; i++) { 
inputBtn[i].addEventListener('click', function () { 
inputBtn[active].focus(); 
}, false); 
inputBtn[i].addEventListener('focus', function () { 
this.addEventListener('keyup', listenKeyUp, false); 
}, false); 
inputBtn[i].addEventListener('blur', function () { 
this.removeEventListener('keyup', listenKeyUp, false); 
}, false); 
} 
/** 
* 监听键盘的敲击事件 
*/ 
function listenKeyUp() { 
var beginBtn = document.querySelector('#beginBtn'); 
if (!isNaN(this.value) && this.value.length != ) { 
if (active < ) { 
active += ; 
} 
inputBtn[active].focus(); 
} else if (this.value.length == ) { 
if (active > ) { 
active -= ; 
} 
inputBtn[active].focus(); 
} 
if (active >= ) { 
var _value = inputBtn[active].value; 
if (beginBtn.className == 'begin-no' && !isNaN(_value) && _value.length != ) { 
beginBtn.className = 'begin'; 
beginBtn.addEventListener('click', function () { 
calculate.begin(); 
}, false); 
} 
} else { 
if (beginBtn.className == 'begin') { 
beginBtn.className = 'begin-no'; 
} 
} 
} 
})(window, document); 

首先监听最外层div,当用户点击div时,将焦点设置到当前active索引对应的input上。active作为计数器,初始值为0(即第一位)。输入有效数字后,active值加1,焦点随之移至下一位,实现输入一位自动跳转的功能。同时监听退格键,按下时active减1,焦点前移。当input失去焦点时,移除相关监听事件,防止重复触发。

梳理后可见,该效果核心在于焦点位置的精准控制,整体逻辑并不复杂。组件的重点更多在于CSS样式的精细还原,JavaScript部分相对简单。最后祝大家元旦快乐。

以上代码简要介绍了JavaScript实现仿支付宝密码输入框的全过程,希望读者能够喜欢。

作者最新文章