[英]Change input to uppercase without the cursor jumping to the end of the text
我正在使用以下代码将我的输入值更改为大写:
<script>
function uppercase(z){
v = z.value.toUpperCase();
z.value = v;
}
</script>
<input type="text" id="example" onkeyup="uppercase(this)">
问题是当我在文本中间输入一些东西时,光标会跳到它的末尾。 在 Google 上搜索我尝试遵循代码,但它根本不起作用:
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.
});
}
第一个代码工作正常,但我仍然不知道如何防止光标跳转。
您可以通过简单地添加一些 CSS 样式来实现这一点:
#example {
text-transform: uppercase;
}
这将使输入字段中的所有字母都显示为大写,但值仍然相同。 如果您需要将值设为大写,请在需要时将其转换为大写(例如,在提交之前)
您还可以在 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>
我一直在寻找解决同一问题的方法。
添加 CSS 对我有用,但有一个特定要求,即我们的后端 api 只接受大写字符串。
所以除了:
#example {
text-transform: uppercase;
}
我还添加了侦听onBlur
和keydown.enter
回调,并在这些事件被触发时将输入值转换为大写。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.