当前位置:首页 > JavaScript

js 实现游标_

2026-03-13 20:11:40JavaScript

使用 JavaScript 实现游标

在 JavaScript 中,可以通过操作 DOM 元素的 selectionStartselectionEnd 属性来实现游标控制。以下是一些常见的方法:

获取当前游标位置

const inputElement = document.getElementById('myInput');
const cursorPosition = inputElement.selectionStart;
console.log(cursorPosition); // 输出当前游标位置

设置游标位置

const inputElement = document.getElementById('myInput');
inputElement.selectionStart = 5;
inputElement.selectionEnd = 5;
inputElement.focus(); // 确保元素获得焦点

选中文本范围

const inputElement = document.getElementById('myInput');
inputElement.selectionStart = 2;
inputElement.selectionEnd = 5;
inputElement.focus();

在文本框中插入文本并移动游标

const inputElement = document.getElementById('myInput');
const cursorPos = inputElement.selectionStart;
const textBefore = inputElement.value.substring(0, cursorPos);
const textAfter = inputElement.value.substring(cursorPos);
inputElement.value = textBefore + '新文本' + textAfter;
inputElement.selectionStart = cursorPos + '新文本'.length;
inputElement.selectionEnd = cursorPos + '新文本'.length;
inputElement.focus();

处理多行文本框的游标

对于 textarea 元素,可以使用相同的方法:

const textareaElement = document.getElementById('myTextarea');
textareaElement.selectionStart = 10;
textareaElement.selectionEnd = 10;
textareaElement.focus();

使用 setSelectionRange 方法

某些情况下,可以使用 setSelectionRange 方法更简洁地设置游标位置:

js 实现游标_

const inputElement = document.getElementById('myInput');
inputElement.setSelectionRange(3, 3);
inputElement.focus();

这些方法适用于大多数现代浏览器,可以满足基本的游标控制需求。

标签: 游标js
分享给朋友:

相关文章

jquery js

jquery js

jQuery 简介 jQuery 是一个快速、简洁的 JavaScript 库,简化了 HTML 文档遍历、事件处理、动画和 Ajax 交互。它兼容多种浏览器,提供易于使用的 API,使开发者能够更高…

js类实现

js类实现

使用类实现 JavaScript 功能 在 JavaScript 中,类(Class)是一种语法糖,基于原型继承机制。通过 class 关键字可以更直观地定义对象模板。 基本类定义 class…

节流js实现

节流js实现

节流(Throttle)的实现原理 节流是一种限制函数执行频率的技术,确保函数在一定时间间隔内最多执行一次。适用于高频触发事件(如滚动、输入、窗口调整等)的场景。 基础实现方式 使用时间戳判断是否执…

js实现跑马灯

js实现跑马灯

实现跑马灯效果 使用HTML和JavaScript可以轻松实现跑马灯效果。以下是两种常见的实现方式: HTML结构 <div id="marquee"> <span>…

js实现图片

js实现图片

图片加载与显示 在JavaScript中,可以通过Image对象动态加载图片。创建实例后设置src属性触发加载,通过onload回调处理加载完成后的操作: const img = new Ima…

js实现路由

js实现路由

js实现路由的方法 在JavaScript中实现路由功能可以通过多种方式完成,以下是几种常见的方法: 使用原生JavaScript实现路由 通过监听window.onhashchange事件来实现基…