JavaScript实现PC端四格密码输入框

作者:代码拾荒

时间:2026-10-24

浏览:195

本文介绍如何使用JavaScript结合jQuery实现PC端的四格密码输入框功能。通过HTML定义四个独立的密码输入框,利用CSS设置样式,并编写JavaScript代码监听input事件,实现自动聚焦和光标跳转,提升用户输入体验。

文章目录

JavaScript实现PC端四格密码输入框

本文分享了一个使用JavaScript实现的PC端四格密码输入框的具体代码示例,供读者参考学习。

HTML部分代码如下:

这是一个简洁的演示示例。


<!DOCTYPE html>
<html>
 <head>
 <meta charset="UTF-8">
 <title>四个密码输入框</title>
 <script type="text/javascript" src="jquery.min.js" ></script>
 </head>
 <style type="text/css">
 input{
 width:40px;
 height:40px;
 text-align: center;
 font-size:22px;
 }
 </style>
 <body>
 支付密码
 <input type="password" name="pwd1" maxlength="1"/>
 <input type="password" name="pwd2" maxlength="1"/>
 <input type="password" name="pwd3" maxlength="1"/>
 <input type="password" name="pwd4" maxlength="1"/>
 </body>
 <script>
 //必须引入jquery才可以用
 //1:当输入框1输入1个字符后,自动切换光标到输入框2
 $(document).ready(function(){
 $("[name='pwd1']").bind("input",function(){
 if($(this).val().length==1){
 $("[name='pwd2']").focus();
 }
 })
 $("[name='pwd2']").bind("input",function(){
 if($(this).val().length==1){
 $("[name='pwd3']").focus();
 }else if($(this).val().length==0){
 $("[name='pwd1']").focus();
 }
 })
 $("[name='pwd3']").bind("input",function(){
 if($(this).val().length==1){
 $("[name='pwd4']").focus();
 }else if($(this).val().length==0){
 $("[name='pwd2']").focus();
 }
 })
 $("[name='pwd4']").bind("input",function(){
 if($(this).val().length==0){
 $("[name='pwd3']").focus();
 }
 
 })
 })
 </script>
</html>

以上就是本文的全部内容,希望能为各位的学习带来帮助,同时也欢迎大家继续支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章