一个半月了,都感受写博客有些生疏了。此次换成了word2016来写,也不知道版式会怎么样。。。你们就将就着看吧~离上次写摇骰子已通过去了一个多月了,期间通过了双十一和双十二的活动,又积攒了一些素材,又能够有的记录咯~前端
可是由于人太懒了。。。不少的东西都没有整理出来,此次就介绍一个如今不少前端都在用的效果吧,但愿能给即将作毕设的各位小伙伴一点帮助吧~浏览器
如今不少时候你们付款的场景都是在手机上面,而随着H5页面的开发变得愈来愈方便,不少场景也从客户端搬到了浏览器中,其中支付这个场景就很天然的被放在了浏览器中。那么这样的输入框你们必定不会陌生吧:this

那么今天我就用JavaScript代码来实现这个效果吧,那么首先介绍一下整个的思路,首先咱们先将肯定输入密码的位数,个人需求是5位,那么就用一个div标签包住5个input标签。spa
而且给这个5个input设置display: inline-block 属性,同时用<!- ->来消除元素直接的margin值,那么HTML就是以下的样子:blog
-
<div class="input">
-
<input type="tel" placeholder="随" maxlength="1"><!-
-
-><input type="tel" placeholder="机" maxlength="1"><!-
-
-><input type="tel" placeholder="5" maxlength="1"><!-
-
-><input type="tel" placeholder="位" maxlength="1"><!-
-
-><input type="tel" placeholder="数" maxlength="1">
-
</div>
在代码中咱们须要设置最多输入的位数,否则就不像了嘛~固然为了在移动端输入的时候能唤起数字键盘来,咱们也须要设置type="tel"。那么接下来就是CSS样式的代码了,这里我就简单的贴出一些代码,具体高仿的像不像其实就是这里了~事件
-
.input {
-
display: inline-block;
-
&:last-child {
-
border-right: 1px solid #999;
-
}
-
input {
-
border-top: 1px solid #999;
-
border-bottom: 1px solid #999;
-
border-left: 1px solid #999;
-
width: 45px;
-
height: 45px;
-
outline:none;
-
font-family: inherit;
-
font-size: 28px;
-
font-weight: inherit;
-
text-align: center;
-
line-height: 45px;
-
color: #c2c2c2;
-
background: rgba(255,255,255,0);
-
}
-
}
那么接下来就是最关键的JavaScript部分了,ip
-
/**
-
* 模拟支付宝的密码输入形式
-
*/
-
(function (window, document) {
-
var active = 0,
-
inputBtn = document.querySelectorAll('input');
-
for (var i = 0; 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 != 0) {
-
if (active < 4) {
-
active += 1;
-
}
-
inputBtn[active].focus();
-
} else if (this.value.length == 0) {
-
if (active > 0) {
-
active -= 1;
-
}
-
inputBtn[active].focus();
-
}
-
if (active >= 4) {
-
var _value = inputBtn[active].value;
-
if (beginBtn.className == 'begin-no' && !isNaN(_value) && _value.length != 0) {
-
beginBtn.className = 'begin';
-
beginBtn.addEventListener('click', function () {
-
calculate.begin();
-
}, false);
-
}
-
} else {
-
if (beginBtn.className == 'begin') {
-
beginBtn.className = 'begin-no';
-
}
-
}
-
}
-
})(window, document);
首先咱们对最外层的div进行监听,当发现用户选择div的时候就将input的焦点设置到active上面去,而这个active则是一个计数器,默认的时候是第一位的,也就是0,而当咱们输入了正确的数字后将会增长一个active,这样input的焦点就会向后移动了,这样就完成了输入一个向后移动一位的功能了,而同时咱们监听键盘上的退格键,当用户点击了退格键以后就对active减一,这样输入框的焦点也就向前移动了,固然,当input失去焦点的时候咱们也同时移除绑定在上面的监听事件,这样就不会形成屡次触发的问题了。支付宝
其实这样梳理下来会发现整个效果仍是很简单的,只须要控制好一个焦点的移动就行了,而我以为整个组件的重点仍是在CSS样式的模仿上面~毕竟JavaScript的逻辑没有什么难的~最后祝你们元旦快乐啦~(*^__^*) ~~开发
---jonnyfrem