将输入更改为大写,光标不会跳到文本末尾

Doc*_*edo 5 javascript input uppercase

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

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

<input type="text" id="example" onkeyup="uppercase(this)">
Run Code Online (Sandbox Code Playgroud)

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

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.
    });
}
Run Code Online (Sandbox Code Playgroud)

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

lfs*_*ndo 5

您还可以在 keyup 上设置光标位置(或者您正在使用的任何内容,只要您获得对输入元素的引用)

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();
}
Run Code Online (Sandbox Code Playgroud)
<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>
Run Code Online (Sandbox Code Playgroud)

链接到代码笔


Lau*_*ens 0

您只需添加一些 CSS 样式即可实现此目的:

#example {
    text-transform: uppercase;
}
Run Code Online (Sandbox Code Playgroud)

这将使输入字段中的所有字母显示为大写,但值仍然相同。如果您需要将该值设置为大写,请在需要时将其转换为大写(例如在提交之前)