我有一个输入,并且该输入的限制为 10。如果用户要删除或退格数字数组中间的数字之一,则光标或退格线现在位于数组的末尾,而不是比用户第一次选择要放置退格键的位置。我希望这样当用户选择这个数字数组并想要删除中间的两个数字时,他们可以这样做,而无需退格光标跳转到数字数组的末尾。 jsfiddle
HTML
<div>
<input type="text" id="test" name="test" style="width: 210px;" maxlength="10" />
</div>
JS
var y = function (e) {
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
e.target.value = !x[2] ? x[1] : x[1] + x[2] + (x[3] ? x[3] : '');
var last = x[3];
};
document.getElementById('test').addEventListener('input', y);
最佳答案
只需记住位置,然后在完成操作后更新位置。
var y = function(e) {
var target = e.target;
var x = e.target.value.replace(/\D/g, '').match(/(\d{0,3})(\d{0,3})(\d{0,4})/);
var value = !x[2] ? x[1] : x[1] + x[2] + (x[3] ? x[3] : '');
if (value === e.target.value) {
return;
}
var position = target.selectionStart;
e.target.value = value;
target.selectionEnd = position; // set the cursor on desired position.
};
document.getElementById('test').addEventListener('input', y);
//In order to avoid jumb behaviour when press non-numeric like a-z
document.getElementById('test').addEventListener('keypress', function(e) {
if (e.which < 48 || e.which > 57) {
e.preventDefault();
}
});
关于javascript - 退格正则表达式返回到输入的正则表达式数组值的末尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42631780/