将输入更改为大写,光标不会跳到文本末尾 [英] Change input to uppercase without the cursor jumping to the end of the text

查看:31
本文介绍了将输入更改为大写,光标不会跳到文本末尾的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using the following code to change my input value to uppercase:

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

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

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

The problem is that when I type something in the middle of the text, the cursor jumps to the end of it. Searching on Google I tried to following code but it didn't work at all:

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.
    });
}

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

The first code is working fine, but I still don't know how to prevent the cursor from jumping.

推荐答案

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

You can achieve this by simply adding some CSS styling:

#example {
    text-transform: uppercase;
}

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

This will make all the letters in the input field appear as uppercase, but the value would still be the same. If you need the value to be uppercase, transform it to uppercase the moment you need it (right before a submit for example)

这篇关于将输入更改为大写,光标不会跳到文本末尾的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆