js-控制输入框输入数字且每隔四个字符增加一个中横线

<input type="tel"  id="inputCode" oninput="value=value.replace(/[^d|-]/g,'')" onfocus="this.placeholder=''" onblur="inputBlur()" placeholder="请输入激活码"  onkeyup="inputCodeUp(event)">

function inputCodeUp(e) {
var inputCode = document.getElementById("inputCode");
var val = inputCode.value;
var str = val.split("")
var targetStr = str[str.length - 1];
if(targetStr == '-') {
inputCode.value = val.substring(0, val.length - 1);
} else if((event.keyCode == 8) && ((val.length + 1) % 5 == 0)) {
inputCode.value = val.substring(0, val.length - 1);
} else
if((val != '-' && event.keyCode != 8)) {
if(val.length % 5 == 0) {
var strs = '';
for(var i = 0; i < str.length - 1; i++) {
strs += str[i];
}
inputCode.value = strs + "-" + targetStr;
}
}
}

原文地址:https://www.cnblogs.com/LindaBlog/p/12698955.html