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

如何在Playwright中将光标定位到输入框末尾?

解决方案

针对输入框光标定位到末尾的需求,有两种常用实现方式,可根据输入框类型选择:

方法一:模拟按下End键(适用于普通input/textarea)

直接通过press方法发送End按键事件,快速将光标移至输入框末尾:

const input = page.locator(`[data-testid='INPUT_FIELD']`)
await input.focus();
// 光标移至末尾
await input.press('End');
await input.type(' remaining part of the message');

方法二:通过JavaScript设置光标(适用于富文本编辑器/contenteditable元素)

如果是富文本编辑区域(比如contenteditable="true"的元素),部分场景下End键可能不生效,可通过执行DOM操作精准定位光标:

const input = page.locator(`[data-testid='INPUT_FIELD']`)
await input.focus();
// 执行JS将光标移至内容末尾
await input.evaluate(el => {
  el.focus();
  const range = document.createRange();
  range.selectNodeContents(el);
  range.collapse(false); // false表示折叠到内容末尾
  const selection = window.getSelection();
  selection.removeAllRanges();
  selection.addRange(range);
});
await input.type(' remaining part of the message');

内容的提问来源于stack exchange,提问作者Andrea Costanzo

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.31 01:45:44