js实现光标
光标定位与操作
在JavaScript中,操作光标通常涉及DOM元素的文本选择范围(Selection API)或输入框的光标位置(如<input>或<textarea>)。以下是常见的光标操作方法:
获取光标位置
const input = document.getElementById('myInput');
const cursorPos = input.selectionStart; // 获取起始位置
const cursorEnd = input.selectionEnd; // 获取结束位置(若未选中文本,则等于起始位置)
设置光标位置
input.setSelectionRange(2, 2); // 将光标定位到第2个字符后
input.focus(); // 确保输入框获得焦点
选中文本
input.setSelectionRange(0, 5); // 选中前5个字符
处理多行文本的光标
对于可编辑元素(如contenteditable的<div>),需使用Range和Selection API:
const editableDiv = document.getElementById('editableDiv');
const range = document.createRange();
const selection = window.getSelection();
range.selectNodeContents(editableDiv); // 选中整个内容
range.collapse(false); // 光标移至末尾
selection.removeAllRanges();
selection.addRange(range);
监听光标事件
通过oninput或onkeyup事件动态跟踪光标位置:
input.addEventListener('keyup', () => {
console.log('当前光标位置:', input.selectionStart);
});
跨浏览器兼容性
旧版IE需使用document.selection代替:
if (document.selection) {
const range = document.selection.createRange();
range.moveStart('character', 2); // IE下的光标移动
}
实际应用示例
自动聚焦并定位到输入框末尾
function focusAtEnd(inputElement) {
inputElement.focus();
const length = inputElement.value.length;
inputElement.setSelectionRange(length, length);
}
插入文本并保持光标位置

function insertTextAtCursor(text) {
const start = input.selectionStart;
const end = input.selectionEnd;
input.value = input.value.substring(0, start) + text + input.value.substring(end);
input.setSelectionRange(start + text.length, start + text.length);
}






