JavaScript实现PC端四格密码输入框
作者:代码拾荒时间:2026-10-24 03:52:34浏览:196
本文介绍如何使用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>
以上就是本文的全部内容,希望能为各位的学习带来帮助,同时也欢迎大家继续支持本站。
作者最新文章
JavaScript异步发送HTTP请求时怎么优雅地处理错误
2026-11-05 17:10:44
5款主流JS在线运行工具对比:CodePen、JSFiddle与StackBlitz怎么选
2026-11-05 17:04:04
JavaScript入门书籍避坑:这些书不适合初学者
2026-11-05 16:31:15
JS使用Math.round实现保留两位小数的原理与代码
2026-11-05 15:35:55
JavaScript 原生 Date 对象怎么实现日期加减
2026-11-05 14:30:00
