HTMLInputElement.setSelectionRange
方法可以从一个被 focused 的 <input>
元素中选中特定范围的内容。
在较新的浏览器中,你可以通过一个可选的 selectionDirection 来指定文本选中过程中的方向。比如通过点击和拖动从结束位置往起始位置选中一个字符串。
每次调用这个这个方法会更新 HTMLInputElement 的 selectionStart
, selectionEnd
,和 selectionDirection
属性。
语法
inputElement.setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection);
参数
selectionStart
被选中的第一个字符的位置。selectionEnd被选中的最后一个字符的 下一个 位置。selectionDirection (可选)一个指明选择方向的字符串,有"forward","backward"和"none" 3个可选值, 分别表示"从前往后", "从后往前"和"选择方向未知或不重要"。
例子
<!DOCTYPE html> <html> <head> <meta charset=utf-8> <title>JS Bin</title> <script> function SelectText () { var input = document.getElementById("mytextbox"); input.focus(); input.setSelectionRange(2,5); // 选择特定部分 input.setSelectionRange(0, -1); // 全选 } </script> </head> <body> <p><input type="text" id="mytextbox" size="20" value="Mozilla"/></p> <p><button onclick="SelectText()">Select text</button></p> </body> </html>
实现效果