输入框自动切换光标demo

关于多输入框自动切换光标及粘贴功能(代码仅供参考可以直接用)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54

//js代码:如下功能实现了输入框的粘贴切换光标问题


//按多长间隔截取字符串,n为长度,返回按长度分割成的字符串数组;
String.prototype.StrCut2Arr = function (n) {
var str = this;
var arr = [];
var len = Math.ceil(str.length / n);
for (var i = 0; i < len; i++) {
if (str.length >= n) {
var strCut = str.substring(0, n);
arr.push(strCut);
str = str.substring(n);
} else {
str = str;
arr.push(str);
}
}
return arr;
}


$('.slinput').bind('input propertychange', function () {
// 删除往前 添加往后
$(this).index();
if ("slinput" == this.className) {
var thisName = this.name;
if ($("#" + thisName).val().trim().length == 4) {
$(this).next('input').focus();
} else if ($("#" + thisName).val().trim().length > 4) {
var strContent = $("#" + thisName).val().trim().replace(/-/g, "");
$('.slinput').val("");
const foo = strContent.StrCut2Arr(4);
if (foo.length >= 4) {
for (let i = 0; i < 4; i++) {
let inputIndex = $(".slinput").get(i);
let inputName = inputIndex.name;
$("#" + inputName).val(foo[i]);
}
} else {
for (let i = 0; i < foo.length; i++) {
let inputIndex = $(".slinput").get(i);
let inputName = inputIndex.name;
$("#" + inputName).val(foo[i]);
}
}

}
if ($("#" + thisName).val().trim().length < 1) {
$(this).prev('input').focus();
}
}
})

//简单的输入框切换光标代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

$('#num_input input').keyup(function (event) {
// 删除往前 添加往后
var this_name = this.name;
// .trim()
if ($("#" + this_name).val().trim().length >= 4) {
$(this).next('input').focus();
}
if ($("#" + this_name).val().trim().length < 1) {
if (event.keyCode == 46 || event.keyCode == 8) {
$(this).prev('input').focus();
}
}
})

注:根据自身业务的需求上面两组代码任选一种即可。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

//页面代码如下:

<div class="slbh" id="num_input">
<input type="text" placeholder="xxxx" class="slinput" style="margin-left: 0;" name="sic_a"
id="sic_a" onfocus="this.placeholder=''" onblur="this.placeholder='xxxx'"/>
<input type="text" placeholder="xxxx" class="slinput" name="sic_b" id="sic_b"
onfocus="this.placeholder=''" onblur="this.placeholder='xxxx'"/>
<input type="text" placeholder="xxxx" class="slinput" name="sic_c" id="sic_c"
onfocus="this.placeholder=''" onblur="this.placeholder='xxxx'"/>
<input type="text" placeholder="xx" maxlength="2" class="slinput" name="sic_d" id="sic_d"
onfocus="this.placeholder=''" onblur="this.placeholder='xx'"/>
</div>