前端的朋友可能遇到過這樣的需求,要求在頁面輸入一串序列號,或激活碼(就像在PC正版軟件中的序列號),可是HTML中並沒有為我們提供類似的組件,我們來自己實現一個:
大體的思路是在表單里有一個隱藏的input,而表面上用一組input代替:
1 <form name="" action="" method="post"> 2 <p> 3 <label>請輸入激活碼:</label> 4 <span class="act-code-group"> 5 <input id="act-code-item-1" name="act-code-item-1" class="act-code-item" type="text" /> - 6 <input name="act-code-item-2" class="act-code-item" type="text" /> - 7 <input name="act-code-item-3" class="act-code-item" type="text" /> - 8 <input name="act-code-item-4" class="act-code-item" type="text" /> 9 </span> 10 <input class="act-code-hidden" type="hidden" value="" /> 11 </p>
至於式樣上的東西就留給大家,自己發揮吧!
然后我們來處理一下相關邏輯:
1 function initActCodeGroup(dom){ 2 var $ = jQuery; 3 var actCodeGroup = dom, 4 actCodeItem = actCodeGroup.find('.act-code-item'); 5 var ctrlPress = false; 6 //actCodeItem.attr('maxlength', '5'); 7 actCodeItem.keyup(function(e){ 8 var oldVal = $(this).val(); 9 if(e.keyCode === 8){ 10 // backspace 11 if(oldVal.length <= 0){ 12 $(this).prev().focus(); 13 } 14 }else if(e.keyCode === 86 && ctrlPress){ 15 //ctrl + v 16 var parseTxt = $(this).val(), 17 parseTxtLen = parseTxt.length; 18 19 ctrlPress = false; 20 21 var actCodes = []; 22 if(parseTxt.indexOf('-') >= 0){ 23 actCodes = parseTxt.split('-'); 24 }else{ 25 if(parseTxtLen >= 4){ 26 actCodes.push(parseTxt.substr(0, 4)); 27 }else{ 28 actCodes.push(parseTxt.substr(0, parseTxtLen)); 29 } 30 if(parseTxtLen >= 8){ 31 actCodes.push(parseTxt.substr(4, 4)); 32 }else{ 33 actCodes.push(parseTxt.substr(4, parseTxtLen-4)); 34 } 35 if(parseTxtLen >= 12){ 36 actCodes.push(parseTxt.substr(8, 4)); 37 }else{ 38 actCodes.push(parseTxt.substr(8, parseTxtLen-8)); 39 } 40 if(parseTxtLen >= 16){ 41 actCodes.push(parseTxt.substr(12, 4)); 42 }else{ 43 actCodes.push(parseTxt.substr(12, parseTxtLen-12)); 44 } 45 } 46 47 if(actCodes.length > 1){ 48 var curInput = $(this); 49 $.each(actCodes, function(i, v){ 50 if(curInput && v.length <= 4){ 51 curInput.val(v); 52 curInput = curInput.next(); 53 }else{ 54 return false; 55 } 56 }); 57 } 58 59 }else if(e.keyCode === 17){ 60 setTimeout(function(){ 61 ctrlPress = false; 62 }, 1000); 63 }else{ 64 if(oldVal.length >= 4){ 65 $(this).val(oldVal.substr(0,4)); 66 if($(this).next().length > 0){ 67 $(this).next().focus(); 68 } 69 } 70 } 71 }).keydown(function(e){ 72 if(e.keyCode === 17){ 73 ctrlPress = true; 74 } 75 }); 76 }
這樣就實現了4*4的序列號組件,接下來調用這個初始化函數就好了
$(document).ready(function(){ initActCodeGroup($('.act-code-group'));
});
打開瀏覽器看看我們的序列號組件吧!