HTMLInputElement.setRangeText() - Web APIs 编辑
The HTMLInputElement.setRangeText()
method replaces a range of text in an <input>
or <textarea>
element with a new string.
Syntax
element.setRangeText(replacement); element.setRangeText(replacement, start, end [, selectMode]);
Parameters
replacement
- The string to insert.
start
Optional- The 0-based index of the first character to replace. Defaults to the current
selectionStart
value (the start of the user's current selection). end
Optional- The 0-based index of the character after the last character to replace. Defaults to the current
selectionEnd
value (the end of the user's current selection). selectMode
Optional- A string defining how the selection should be set after the text has been replaced. Possible values:
"select"
selects the newly inserted text."start"
moves the selection to just before the inserted text."end"
moves the selection to just after the inserted text."preserve"
attempts to preserve the selection. This is the default.
Example
Click the button in this example to replace part of the text in the text box. The newly inserted text will be highlighted (selected) afterwards.
HTML
<input type="text" id="text-box" size="30" value="This text has NOT been updated.">
<button onclick="selectText()">Update text</button>
JavaScript
function selectText() {
const input = document.getElementById('text-box');
input.focus();
input.setRangeText('ALREADY', 14, 17, 'select');
}
Result
Specifications
Specification | Status | Comment |
---|---|---|
HTML Living Standard The definition of 'HTMLInputElement.setSelectionRange()' in that specification. | Living Standard | No change |
HTML5 The definition of 'HTMLInputElement.setSelectionRange()' in that specification. | Recommendation | Initial definition |
Browser compatibility
BCD tables only load in the browser
See also
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论