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

我有一个输入,我想在 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">

https://stackoverflow.com/questions/63942064/

相关文章:

tensorflow - Keras SavedModel 与 Tensorflow SavedMo

linux - 是否可以为 `git clone` 操作指定超时?

python-3.x - 如何创建 swagger :response that produces

python - 如何在 Kotlin 中正确反转链表?

postgresql - Cloud SQL (postgres) 外部数据包装器连接超时到副本实例

python - 为什么 Keras 不返回 lstm 层中细胞状态的完整序列?

javascript - 如何在 react 中的不同组件库之间共享上下文?

angular - 如何避免@types 包引入的补丁级别增加带来重大变化的问题?

gradle - React Native 项目 Android Gradle Fail (Reac

python - 有没有办法在 python 中抓取没有 Selenium 的 JavaScript