input依次输入密码

时间:2022-04-28 13:06:56

原理:

  一个真正的可以输入的input框,opacity: 0,设定位层级;(视图不可见的)

  再来6(n)个input,readyonly,用来显示,type为password,设置好样式;(视图可见的)

  代码如下:

<!DOCTYPE html>
<html> <head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1">
<title>手机端六位密码输入</title>
<script src="http://zeptojs.com/zepto.min.js"></script>
<style>
* {
padding: 0px;
margin: 0px;
} input {
border: none;
outline: none;
background: none;
} #pwd-box {
width: 310px;
height: 48px;
position: relative;
border: 1px solid #9f9fa0;
border-radius: 3px;
overflow: hidden;
margin: 10px auto;
} #pwd-box input[type="number"] {
width: %;
height: %;
color: transparent;
/*letter-spacing 属性增加或减少字符间的空白,字间距*/
letter-spacing: 35px;
position: absolute;
top: ;
left: ;
border: none;
font-size: 18px;
filter: alpha(opacity=);
-moz-opacity: ;
-khtml-opacity: ;
opacity: ;
z-index: ;
outline: none;
} #pwd-box .fake-box {
width: %;
height: %;
display: -webkit-box;
display: -webkit-flex;
display: -ms-flexbox;
display: flex;
-webkit-flex-flow: row;
-ms-flex-flow: row;
flex-flow: row;
} #pwd-box .fake-box input {
-webkit-box-flex: ;
-webkit-flex: ;
-ms-flex: ;
flex: ;
width: %;
height: %;
border: none;
border-right: 1px solid #e5e5e5;
text-align: center;
font-size: 30px;
float: left;
} #pwd-box .fake-box input:nth-last-child() {
border: none;
}
</style>
</head> <body>
<div id="pwd-box">
<input type="number" maxlength="" class="pwd-input" id="pwd-input" autofocus>
<div class="fake-box">
<input type="password" readonly="">
<input type="password" readonly="">
<input type="password" readonly="">
<input type="password" readonly="">
<input type="password" readonly="">
<input type="password" readonly="">
</div>
</div>
<script>
$("#pwd-input").on("input", function() {
// trim(): 去两边空格的方法;
var pwd = $(this).val().trim();
var len = pwd.length;
for(var i = ; i < len; i++) {
$(".fake-box input").eq(i).val(pwd[i]);
}
$(".fake-box input").each(function() {
var index = $(this).index();
if(index >= len) {
$(this).val("");
}
});
if(len == ) {
//执行其他操作
setTimeout(function() {
alert('订单已提交')
}, ) }
if(len > ) {
pwd = pwd.substr(, );
$(this).val(pwd);
len = ;
}
});
</script>
</body> </html>