難點(diǎn)不是插入空格,而是修正光標(biāo)的位置,這個(gè)只支持IE9+、chrome瀏覽器
注意:這個(gè)使用了jquery框架
核心代碼
$(function() { $('#kahao').on('keyup', function(e) { //只對輸入數(shù)字時(shí)進(jìn)行處理 if((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105 )){ //獲取當(dāng)前光標(biāo)的位置 var caret = this.selectionStart //獲取當(dāng)前的value var value = this.value //從左邊沿到坐標(biāo)之間的空格數(shù) var sp = (value.slice(0, caret).match(//s/g) || []).length //去掉所有空格 var nospace = value.replace(//s/g, '') //重新插入空格 var curVal = this.value = nospace.replace(/(/d{4})/g, "$1 ").trim() //從左邊沿到原坐標(biāo)之間的空格數(shù) var curSp = (curVal.slice(0, caret).match(//s/g) || []).length //修正光標(biāo)位置 this.selectionEnd = this.selectionStart = caret + curSp - sp } }) })
完整代碼:已經(jīng)測試
<!DOCTYPE html><html><head lang="en"> <meta charset="UTF-8"> <title>銀行卡號4位空格</title> <script src="http://j2.58cdn.com.cn/js/jquery-1.8.3.js"></script></head><body> <input type="text" id="kahao" /> <script> $(function() { $('#kahao').on('keyup', function(e) { //只對輸入數(shù)字時(shí)進(jìn)行處理 if((e.which >= 48 && e.which <= 57) || (e.which >= 96 && e.which <= 105 )){ //獲取當(dāng)前光標(biāo)的位置 var caret = this.selectionStart //獲取當(dāng)前的value var value = this.value //從左邊沿到坐標(biāo)之間的空格數(shù) var sp = (value.slice(0, caret).match(//s/g) || []).length //去掉所有空格 var nospace = value.replace(//s/g, '') //重新插入空格 var curVal = this.value = nospace.replace(/(/d{4})/g, "$1 ").trim() //從左邊沿到原坐標(biāo)之間的空格數(shù) var curSp = (curVal.slice(0, caret).match(//s/g) || []).length //修正光標(biāo)位置 this.selectionEnd = this.selectionStart = caret + curSp - sp } }) }) </script></body></html>
經(jīng)過測試確實(shí)很好用,里面用到了很多的正則
/s 匹配任何空白字符,包括空格、制表符、換頁符等等。等價(jià)于[ /f/n/r/t/v]。
關(guān)于正則表達(dá)式的教程可以參考這篇文章:
新聞熱點(diǎn)
疑難解答