在input获得焦点时自动选中全部内容,需监听focus事件并调用select()方法;适用于text、search、number(部分浏览器)、textarea等可编辑控件,对password、hidden及readonly/disabled无效。

在 input 获得焦点时自动选中全部内容,只需监听 focus 事件并调用 select() 方法即可。
使用 focus 事件配合 select() 方法
当用户点击或通过 Tab 键聚焦到输入框时,触发 focus 事件,此时调用元素的 select() 方法就能高亮选中全部文本。
- 适用于
<input type="text">、<input type="search">、<input type="number">(部分浏览器支持)、<textarea>等可编辑表单控件 - 注意:对
type="password"或type="hidden"无效;readonly或disabled状态下也不会触发或生效 - 推荐在 DOM 加载完成后绑定,避免元素尚未存在
基础写法(原生 JavaScript)
直接为单个 input 绑定:
document.getElementById('myInput').addEventListener('focus', function() {
this.select();
});
批量处理多个 input(如所有 class 为 auto-select 的输入框):
立即学习“Java免费学习笔记(深入)”;
document.querySelectorAll('input.auto-select, textarea.auto-select').forEach(el => {
el.addEventListener('focus', () => el.select());
});
兼容性与注意事项
现代浏览器均支持 select(),但有几点需留意:
- 若 input 内容为空,
select()不会报错,但无视觉效果 - 在某些移动端(如 iOS Safari),
focus后立即select()可能被忽略,可加微小延迟:setTimeout(() => this.select(), 0) - 如果用了 Vue/React 等框架,应在组件挂载后(如
mounted或useEffect)绑定,避免操作未渲染的 DOM
结合 click 事件增强体验(可选)
有些用户习惯点击输入框再编辑,为提升响应感,可同时监听 click 事件(尤其适合初始聚焦不明显的情况):
const input = document.getElementById('myInput');
input.addEventListener('focus', () => input.select());
input.addEventListener('click', () => input.select());
注意:这样不会导致重复选中,因为 select() 多次调用效果一致。


















