如何删除更改输入字段中光标位置的功能。因此,当用户输入内容时,他们总是会在最后输入内容。
答案 0 :(得分:3)
您可能会遇到一些旧的浏览器限制,但这只是为了让您有所了解。
您需要同时处理paste
和keydown
事件。对于粘贴,您可能需要使用剪贴板API进行救援。足够多的交谈,就可以了:
function setRng(el, txt, from, to) {
el.setSelectionRange(from + txt.length, to + txt.length);
}
function insVal(el, txt, from, to) {
from = Math.max(0, from);
to = to || from;
el.value = el.value.substring(0, from) + txt + el.value.substring(to, el.value.length);
setRng(el, txt, from, from);
}
function writeToEnd(ev) {
var el = ev.target;
var key = ev.keyCode;
var isBackspace = key === 8;
var isPaste = ev.type === "paste";
var txt = isPaste ? (ev.clipboardData || window.clipboardData).getData('Text') : '';
var fromOffset = isBackspace ? -1 : 0;
if (txt && txt.length > 1 || isPaste || isBackspace) ev.preventDefault(); // Cause of some special input
insVal(el, txt, el.value.length + fromOffset, el.value.length);
}
[...document.querySelectorAll('.writeToEnd')].forEach(el => {
el.addEventListener('keydown', writeToEnd);
el.addEventListener('paste', writeToEnd);
});
<input class="writeToEnd" type="text" value="input test"><br>
<textarea class="writeToEnd">textarea test</textarea><br>
(Test also COPY/PASTE using mouse and keyboard)
答案 1 :(得分:1)
此代码不会阻止用户更改光标的位置,但不允许用户在文本之间书写。
请尝试这个
function writeAtLast() {
var textbox = document.getElementById('text');
textbox.setSelectionRange(textbox.value.length, textbox.value.length);
};
<input id="text" type="text" class="txtbox" onkeypress='writeAtLast()' onCopy="return false" onDrag="return false" onDrop="return false" onPaste="writeAtLast()" autocomplete=off />
答案 2 :(得分:-1)
function changeCursorPosition() {
var ele = document.getElementById('txt');
//set cursor position here
ele.setSelectionRange(1, 1);
};
<input type="text" id="txt" onkeypress="changeCursorPosition()" />