一個半月了,都感受寫博客有些生疏了。此次換成了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