相关疑难解决方法(0)

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

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

<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)

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

javascript input uppercase

5
推荐指数
2
解决办法
2932
查看次数

标签 统计

input ×1

javascript ×1

uppercase ×1