如何在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
相关产品推荐
相关产品推荐

