当输入大小正好是两个时,我试图插入一个连字符。这是我的代码
document.getElementById('numberInput').onkeypress = function() {
if (this.value.length == 2) {
this.value = this.value + '-';
}
}
<input type="text" id="numberInput">
但问题是 - 在输入第三个字符之前不会出现。虽然连字符放置正确,但我的意思是在两个字符之后。
输入两个字符后如何立即获得连字符?
我试过onkeyup
了,但问题是当我按下退格键时它也会触发。当有两个字符时,会出现连字符,但此时如果我按退格键并删除连字符,它会立即返回。所以我选择onkeypress
输入文本框的值,在onKeyPress期间始终是更改前的值。这允许事件侦听器取消按键。
要在字段值更新后获取值,请安排一个函数在下一个事件循环上运行。执行此操作的常用方法是调用 setTimeout,超时为 0:
document.getElementById('numberInput').onkeypress = function() {
// arrow function keeps scope
setTimeout(() => {
// now it is the value after the keypress
if (this.value.length == 2) {
this.value = this.value + '-';
}
}, 0);
}
<input type="text" id="numberInput">
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句