← 中文资源

简体中文版本

setRangeText 编辑输入框选区

HTMLInputElement.setRangeText 用四种选区模式替换字符区间:select 高亮新串、start/end 移动光标、缺省 preserve;只传替换串时作用于当前选区。

阅读英文原文

使用要点

  • 演示输出是带标签的(select keeps the replacement highlighted、selection mode union is closed:),每个操作都会留下自己的一行标注。

常见问题

复制和运行之间有安装步骤吗?

没有。从复制到运行之间没有别的要做。

核心语句

const mode: 'select' | 'start' | 'end' | 'preserve' = 'preserve';
input.setRangeText('REDACTED', 3, 7, 'select');
declare const input: HTMLInputElement;

代码示例

declare const input: HTMLInputElement;

// 完整签名:替换 [start, end) 并声明替换后的选区位置
input.setRangeText('REDACTED', 3, 7, 'select');
console.log('select keeps the replacement highlighted');

// 'start' / 'end' 把光标放到插入点前后;缺省 'preserve' 尽量保住原选区
input.setRangeText('-', 0, 0, 'end');
const mode: 'select' | 'start' | 'end' | 'preserve' = 'preserve';
input.setRangeText('x', 0, 1, mode);
console.log('selection mode union is closed:', mode);

// 只传替换串:范围取用户当前选区 selectionStart/selectionEnd
input.setRangeText('PASTED');
console.log(input.value);