首页 > 解决方案 > 将输入更改为大写而不使光标跳到文本末尾

问题描述

我正在使用以下代码将输入值更改为大写:

<script>
function uppercase(z){
    v = z.value.toUpperCase();
    z.value = v;
}
</script>

<input type="text" id="example" onkeyup="uppercase(this)">

问题是,当我在文本中间键入内容时,光标会跳到它的末尾。在谷歌上搜索我试图遵循代码,但它根本不起作用:

function uppercase(z){
    document.getElementById(z).addEventListener('input', function (e) {
      var target = e.target, position = target.selectionStart; // Capture initial position
      target.value = target.value.replace(/\s/g, ''); // This triggers the cursor to move.

      v = z.value.toUpperCase();
      z.value = v;

      target.selectionEnd = position; // Set the cursor back to the initial position.
    });
}

第一个代码工作正常,但我仍然不知道如何防止光标跳跃。

标签: javascriptinputuppercase

解决方案


您还可以设置光标位置 onkeyup (或任何您使用的,只要您获得对输入元素的引用)

function withSelectionRange() {
  const elem = document.getElementById('working');
  // get start position and end position, in case of an selection these values
  // will be different
  const startPos = elem.selectionStart;
  const endPos = elem.selectionEnd;
  elem.value = elem.value.toUpperCase();
  elem.setSelectionRange(startPos, endPos);
}

function withoutSelectionRange() {
  const elem = document.getElementById('notWorking');
  elem.value = elem.value.toUpperCase();
}
<div style="display: flex; flex-direction: column">
  <label for='working'>Uppercase text with selection range</label>
  <input id='working' type='text' onkeyup="withSelectionRange()"></input>

  <label for='notWorking'>Uppercase text input without selection range</label>
  <input id='notWorking' type='text' onkeyup="withoutSelectionRange()"></input>
</div>

链接到codepen


推荐阅读