欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

基于jquery實(shí)現(xiàn)的銀行卡號每隔4位自動插入空格的實(shí)現(xiàn)代碼

 更新時間:2016年11月22日 13:25:00   作者:司徒正美  
這篇文章主要介紹了基于jquery實(shí)現(xiàn)的銀行卡號每隔4位自動插入空格的實(shí)現(xiàn)代碼,需要的朋友可以參考下

難點(diǎn)不是插入空格,而是修正光標(biāo)的位置,這個只支持IE9+、chrome瀏覽器

注意:這個使用了jquery框架

核心代碼

$(function() {

      $('#kahao').on('keyup', function(e) {
       //只對輸入數(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ù)字時進(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 匹配任何空白字符,包括空格、制表符、換頁符等等。等價于[ \f\n\r\t\v]。

關(guān)于正則表達(dá)式的教程可以參考這篇文章:

http://www.dbjr.com.cn/tools/zhengze.html

http://www.dbjr.com.cn/tools/regexsc.htm

相關(guān)文章

最新評論