You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用原生JS获取点击按钮前一刻处于激活状态的输入元素

实现方案

核心问题说明

点击插入按钮时,按钮会抢占焦点,直接调用document.activeElement获取到的是当前点击的按钮,而非之前激活的输入框,所以需要提前存储最后一次激活的可输入元素。

相关疑问解答

  • 不存在document.hadFocus方法,原生仅提供document.hasFocus()方法,作用是判断当前整个文档是否处于聚焦状态,无法回溯历史聚焦元素
  • 可以通过focusout事件记录输入框id,但更简便的方案是直接监听focus事件存储元素引用,无需额外通过id查询DOM

完整原生JS实现

// 存储最后一次激活的可输入元素
let lastFocusedInput = null;

// 全局监听focus事件,捕获所有输入框的激活状态
document.addEventListener('focus', (e) => {
  // 可根据需求调整匹配规则,比如过滤密码框、只匹配指定类名的输入框
  if (['INPUT', 'TEXTAREA'].includes(e.target.tagName) && e.target.type !== 'password') {
    lastFocusedInput = e.target;
  }
}, true); // 捕获模式确保动态生成的输入框也能被监听到

// 优化后的光标插入方法
function insertAtCursor(newText, el = lastFocusedInput) {
  // 无有效输入框时直接返回避免报错
  if (!el) return;
  const start = el.selectionStart;
  const end = el.selectionEnd;
  const text = el.value;
  el.value = text.substring(0, start) + newText + text.substring(end);
  // 光标定位到插入内容末尾
  el.selectionStart = el.selectionEnd = start + newText.length;
  el.focus();
}

使用方式

给插入按钮绑定点击事件,直接调用方法传入要插入的内容即可:

// 示例:点击id为insertBtn的按钮插入笑脸符号
document.querySelector('#insertBtn').addEventListener('click', () => {
  insertAtCursor('😊');
});

注意事项

  • 该方案支持动态生成的输入框,不需要给新增输入框单独绑定事件
  • 可以自行修改focus事件中的匹配规则,适配你需要的特定输入框场景

内容的提问来源于stack exchange,提问作者Andrei Cleland

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 09:15:01