setSelectionRange 不是函数

setSelectionRange is not a function

这看起来很简单,但行不通:

document.getElementById('test').setSelectionRange(3,3)
<div id="test">test</div>

Google Chrome.

这是因为 'test' 元素需要是 <input/> 元素。尝试按如下方式修改您的 HTML:

<input id="test" />

还要考虑对 javascript 进行以下更改。通过对您的代码进行这些更新,当您的输入字段中有足够的文本时,您的 javascript 应该会按预期工作。例如,考虑在 "hello world" 中选择 "world" 的代码:

const input = document.getElementById('test');
input.focus();
input.setSelectionRange(6,11);
<input id="test" value="hello world" />

更多信息,see the MDN docs for setSelectionRange()

<input id="test" value="hello world" />

var InputElement = $('test')[0] as HTMLInputElement;
InputElement.setSelectionRange(3, 3);

要在 <div> 上制作它,您应该使其可编辑:

<div id="test" contenteditable="true">test</div>