gpt4 book ai didi

javascript - 使用逗号自动格式化数字时如何保留预期的光标位置?

转载 作者:行者123 更新时间:2023-12-05 08:05:41 24 4
gpt4 key购买 nike

我有一个输入,我想在 keyup 事件中替换数字的值。使用 Intl.NumberFormat().format(num); 来完成这个。

一切都很好,直到您在已经格式化的值内部单击并开始添加更多数字时,光标才会跳动。

我试图通过设置光标来解决这个问题,但它仍然表现不佳。

简而言之,我该如何更改此代码段,以便无论您在何处编辑值,光标都保持在预期位置?

const input = document.getElementById("foo");
input.addEventListener("keyup", handleKeyUp);

function handleKeyUp(e) {
const num = e.target.value.replace(/,/g, "");
const formatted = new Intl.NumberFormat().format(num);

var cursor = e.target.selectionStart;// + 1;
input.value = formatted;
e.target.setSelectionRange(cursor, cursor);
}

// Try the following
// 1) 123456789
// 2) 123
// 3) place cursor between the 1 and 2 and add a number

// If I ++cursor then #1 is resolved
// And #2 initially appears to be resolved unless I keep going with more numbers
<input id="foo" type="text">

最佳答案

这不是一个非常优雅的解决方案,但我根据是否在文本字段中添加/删除逗号(分别向左或向右)移动了光标。

请看下面的片段:

const input = document.getElementById("foo");
input.addEventListener("keyup", handleKeyUp);
let commas = 0;

function handleKeyUp(e) {
const num = e.target.value.replace(/,/g, "");
const formatted = new Intl.NumberFormat().format(num);
// get total commas in number
let totalCommas = (formatted.match(/,/g) || []).length;
var cursor = e.target.selectionStart;

if(commas > totalCommas) {
//shift cursor to the left (a comma was removed)
commas--;
cursor--;
} else if (commas < totalCommas){
// shift cursor to the right (a comma was added)
commas++;
cursor++;
}

input.value = formatted;
e.target.setSelectionRange(cursor, cursor);
}

// Try the following
// 1) 123456789
// 2) 123
// 3) place cursor between the 1 and 2 and add a number

// If I ++cursor then #1 is resolved
// And #2 initially appears to be resolved unless I keep going with more numbers
<input id="foo" type="text">

关于javascript - 使用逗号自动格式化数字时如何保留预期的光标位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63942064/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com