js实现游标
游标的基本概念
游标(Cursor)在JavaScript中通常指代用户在界面上的指针位置或文本选择的光标位置。根据应用场景不同,游标的实现方式也有所差异。
获取输入框游标位置
通过selectionStart和selectionEnd属性可以获取或设置输入框中的游标位置:
const input = document.getElementById('myInput');
// 获取游标位置
const cursorPos = input.selectionStart;
// 设置游标位置
input.setSelectionRange(5, 5);
获取页面中的鼠标游标位置
通过监听mousemove事件获取鼠标在页面中的坐标:
document.addEventListener('mousemove', (event) => {
const x = event.clientX;
const y = event.clientY;
console.log(`Cursor position: (${x}, ${y})`);
});
自定义游标样式
通过CSS修改鼠标指针样式:
body {
cursor: url('custom-cursor.png'), auto;
}
.clickable {
cursor: pointer;
}
文本编辑器中的游标控制
在可编辑元素(contentEditable)中控制游标:
const editor = document.getElementById('editor');
const range = document.createRange();
const node = editor.firstChild;
range.setStart(node, 5);
range.setEnd(node, 5);
const sel = window.getSelection();
sel.removeAllRanges();
sel.addRange(range);
游标位置恢复技巧
保存并恢复输入框的游标位置:
function saveCursorPosition(input) {
return {
start: input.selectionStart,
end: input.selectionEnd,
value: input.value
};
}
function restoreCursorPosition(input, saved) {
if (input.value === saved.value) {
input.setSelectionRange(saved.start, saved.end);
}
}
跨浏览器兼容方案
处理不同浏览器间的游标API差异:
function getCursorPosition(input) {
if ('selectionStart' in input) {
return input.selectionStart;
} else if (document.selection) {
input.focus();
const sel = document.selection.createRange();
sel.moveStart('character', -input.value.length);
return sel.text.length;
}
return 0;
}
虚拟游标实现
在Canvas等非DOM环境中实现虚拟游标:

const canvas = document.getElementById('canvas');
const ctx = canvas.getContext('2d');
let cursorPos = { x: 0, y: 0 };
function drawCursor() {
ctx.clearRect(0, 0, canvas.width, canvas.height);
ctx.fillStyle = 'black';
ctx.fillRect(cursorPos.x, cursorPos.y, 2, 20);
requestAnimationFrame(drawCursor);
}
drawCursor();
这些方法涵盖了JavaScript中游标操作的主要场景,包括输入框游标控制、鼠标位置跟踪、自定义样式以及复杂环境下的游标实现。根据具体需求选择合适的方法即可。






