javascript - 将输入更改为大写而不使光标跳到文本末尾
问题描述
我正在使用以下代码将输入值更改为大写:
<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.
});
}
第一个代码工作正常,但我仍然不知道如何防止光标跳跃。
解决方案
您还可以设置光标位置 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>
推荐阅读
- reactjs - React-Bootsrap 导航栏下拉菜单未关闭
- vim - 从 vim 复制时忽略新行
- typescript - 类型 '() => number' 不可分配给类型 'number'
- java - Netbeans 11.3 未安装 - java.lang.noClassDefFoundError - pack200
- python - Redis 共享资源 - 两个或多个 python 脚本更新相同的哈希但不同的键,会发生什么?
- javascript - 添加一个新的 Ionic 页面
- r - R ggplot 更改轴的标签而不更改比例
- javascript - React中如何调用函数中的函数(认证、路由)
- neo4j - 如何使用 py2neo 读取 csv 文件在 neo4j 中创建不同的关系?
- excel - 将两列表排序为多列表