HTMLInputElement: selectionStart 属性
HTMLInputElement 接口的 selectionStart 属性是一个数字,表示所选文本的起始索引。当没有选择任何文本时,则返回 <input> 元素内文本输入光标(caret)的位置。
注意:根据 WHATWG 表单规范,selectionStart 属性仅适用于 text、search、URL、tel 和 password 类型的 input。在现代浏览器中,在其他类型的 input 上设置 selectionStart 属性会抛出异常。此外,在非文本 input 元素上访问 selectionStart 属性时,此属性返回 null。
如果 selectionStart 大于 selectionEnd,则两者都被视为 selectionEnd 的值。
值
一个非负整数。
示例
HTML
html
<!-- use selectionStart on non text input element -->
<label for="color">selectionStart property on type=color</label>
<input id="color" type="color" />
<!-- use selectionStart on text input element -->
<fieldset>
<legend>selectionStart property on type=text</legend>
<label for="statement">Select 'mdn' word from the text : </label>
<input
type="text"
id="statement"
value="The mdn is a documentation repository." />
<button id="statement-btn">Select mdn text</button>
</fieldset>
JavaScript
js
const inputElement = document.getElementById("statement");
const statementBtn = document.getElementById("statement-btn");
const colorStart = document.getElementById("color");
statementBtn.addEventListener("click", () => {
inputElement.selectionStart = 4;
inputElement.selectionEnd = 7;
inputElement.focus();
});
// open browser console to verify output
console.log(colorStart.selectionStart); // Output : null
结果
规范
| 规范 |
|---|
| HTML # dom-textarea/input-selectionstart |
浏览器兼容性
加载中…