无法删除动态添加的冒号

我需要一个函数,在输入中键入两个数字后会添加冒号(:),我在StackOverflow上找到了这个解决方案 ,这也是我需要的。 它在键入的第二个数字后添加冒号,不会让你添加超过4个数字。

但是,有一个我无法理解和解决的问题。 我需要能够删除所有数字 ,但它不会让我。 我只能删除最后两个,你不能删除冒号。

这是当前的代码:

var time = document.getElementsByClassName('time'); for (var i = 0; i  2 and string is a number if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5 }); }; 

https://jsfiddle.net/bubxm7pe/

您可以使用e.keyCode为退格添加条件

它在这里工作

 if (e.keyCode != 8) { var reg = /[0-9]/; if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5 } 

更新:您还可以使用以下数字限制用户。 它也适用于此

 //called when key is pressed in textbox $(".time").keypress(function (e) { //if the letter is not digit then don't type anything if (e.which != 8 && e.which != 0 && (e.which < 48 || e.which > 57)) { return false; } else { var reg = /[0-9]/; if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number if (this.value.length > 4) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5 } }); 

您可以检查按下的键是否为数字,而不是检查deletebackspace

 if (keycode >= 48 && keycode <= 57) { if (this.value.length == 2 && reg.test(this.value)) this.value = this.value + ":"; //Add colon if string length > 2 and string is a number if (this.value.length > 5) this.value = this.value.substr(0, this.value.length - 1); //Delete the last digit if string length > 5 } 

https://jsfiddle.net/6jbaayqd/

由于您已经倾向于使用regex ,那么为什么不使用它来格式化input字段中的时间 – 请参阅下面的演示:

 document.getElementsByClassName('time')[0].addEventListener('keyup', function(e) { this.value = this.value .replace(/[^\d]/g, '') // allow only digits .replace(/^([\d]{4})\d+$/g, '$1') // restrict to 4 chars .replace(/\B(?=(\d{2})+(?!\d{1}))/g, ":"); // place the colon });