您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

在自定义输入字段中输入数据

在自定义输入字段中输入数据

一个内置的DOM方法document.execCommand。 如果是扩展名,请在内容脚本中使用此代码

document.querySelector('some.selector').focus();
document.execCommand('insertText', false, 'new text')

为当前关注的DOM元素,因此将在字段设置为true的情况下触发所有必需的事件(如beforeinput,,input因此,change如果适用)isTrusted

您可能希望选择当前文本以完全替换它,而不是附加:

replaceValue('some.selector', 'new text');

function replaceValue(selector, value) {
  const el = document.querySelector(selector);
  if (el) {
    el.focus();
    el.select();
    document.execCommand('insertText', false, value);
  }
  return el;
}

请注意,execCommand在2020年被标记为已过时,但是它将在可预见的将来工作,因为新的编辑API规范尚未完成,并且知道此类操作通常需要多长时间才能完成。

其他 2022/1/1 18:16:33 有399人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶