代码实现input的value值选中HTMLInputElement.setSelectionRange()

来源:互联网 发布:产品矩阵是什么意思 编辑:程序博客网 时间:2024/06/06 01:57

假如说有如下的需求: input的value部分有用,部分无用,我们希望input框获取焦点的时候直接选中无用的部分。

我们就需要用到下面的主角:HTMLInputElement.setSelectionRange(),支持我们设置开始位置和结束位置,来实现input的选中效果。

HTMLInputElement.setSelectionRange(selectionStart, selectionEnd, [optional] selectionDirection)

selectionStart:0开始索引的字符开始选定的字符位置;
selectionEnd:0开始索引的字符最后选定的字符后的位置(测试所得:在chrome39版本等旧的浏览器上面,selectionEnd必须是正数,在新版本的chrome62版本上面,selectionEnd可以为负数,表示从字符的最后一位开始算起,比如-1表示最后一位,-2表示倒数第二位);
selectionDirection[可选参数]:forward” or “backward”, or “none”(但是我测试好想不起作用)

下面给一个例子:

<!DOCTYPE html><html><head><meta charset=utf-8><title>input select</title><script>function inputSelect () {    var input = document.getElementById("textbox");    input.focus();    // 下面四种写法效果是一样的,所以设置的selectionDirection好像不起作用    input.setSelectionRange(0, 3);    // input.setSelectionRange(0, -1); //全选的实现方式;chrome62版本新浏览器    // input.setSelectionRange(0, input.value.length); //全选的实现方式;chrome39版本旧浏览器    // input.setSelectionRange(0, 3, "backword");    // input.setSelectionRange(0, 3, "forword");    // input.setSelectionRange(0, 3, "none");}</script></head><body>    <p><input type="text" id="textbox" value="abcdefg"/></p>    <p><button onclick="inputSelect()">Select text</button></p></body></html>

所以说在使用HTMLInputElement.setSelectionRange()的时候,最好的切兼容低版本的方式是不采用负数形式,就好比如全选,初始位置0,终止位置为value的length。

阅读全文
0 0
原创粉丝点击