当前位置:首页 > JavaScript

js实现input选中

2026-03-16 07:44:32JavaScript

选中 input 元素的内容

使用 select() 方法可以选中 input 元素内的文本内容。该方法适用于 <input><textarea> 元素。

document.getElementById('myInput').select();

获取选中文本

通过 selectionStartselectionEnd 属性可以获取选中文本的起始和结束位置。

const input = document.getElementById('myInput');
const startPos = input.selectionStart;
const endPos = input.selectionEnd;
const selectedText = input.value.substring(startPos, endPos);

设置选中范围

使用 setSelectionRange() 方法可以指定选中文本的起始和结束位置。

js实现input选中

document.getElementById('myInput').setSelectionRange(2, 5);

选中全部文本

结合 select() 方法或 setSelectionRange() 方法可以实现全选功能。

const input = document.getElementById('myInput');
input.select();
// 或者
input.setSelectionRange(0, input.value.length);

响应事件触发选中

可以在焦点事件或其他交互事件中触发选中操作。

js实现input选中

document.getElementById('myInput').addEventListener('focus', function() {
  this.select();
});

兼容性注意事项

setSelectionRange() 方法在 IE8 及以下版本不支持,需使用 createTextRange 替代。

const input = document.getElementById('myInput');
if (input.createTextRange) {
  const range = input.createTextRange();
  range.collapse(true);
  range.moveEnd('character', endPos);
  range.moveStart('character', startPos);
  range.select();
} else {
  input.setSelectionRange(startPos, endPos);
}

结合 CSS 增强视觉效果

可以通过 CSS 伪类 :selection 自定义选中文本的样式。

input::selection {
  background-color: #ffb7b7;
  color: #000;
}

标签: jsinput
分享给朋友:

相关文章

js 实现vue

js 实现vue

实现 Vue 的核心功能 在 JavaScript 中实现 Vue 的核心功能需要模拟数据绑定、虚拟 DOM 和响应式系统。以下是一个简化版的实现思路: 响应式系统 通过 Object.define…

js实现图片上传

js实现图片上传

图片上传的基本实现 使用HTML的<input type="file">元素配合JavaScript的File API可以实现图片上传功能。HTML部分需要创建一个文件选择输入框和一个用于…

js实现复制功能

js实现复制功能

使用 document.execCommand 方法 这种方法适用于较旧的浏览器,但在现代浏览器中可能被逐步淘汰。通过创建一个临时的 textarea 元素,将文本内容放入其中,然后执行复制命令。…

js实现图片预览

js实现图片预览

使用FileReader API实现图片预览 通过FileReader对象读取用户选择的图片文件并显示预览: const input = document.getElementById('image…

js 实现vue

js 实现vue

Vue.js 的基本实现 在 JavaScript 中实现 Vue.js 的核心功能,可以通过数据绑定、响应式系统和虚拟 DOM 来实现。以下是实现 Vue.js 核心功能的简化版本。 数据响应式系…

js树实现

js树实现

树的基本概念 树是一种非线性的数据结构,由节点和边组成。每个节点包含一个值和指向子节点的引用。树的顶部节点称为根节点,没有子节点的节点称为叶节点。 树的实现方式 在JavaScript中,树可以通过…