代码实现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
- 代码实现input的value值选中HTMLInputElement.setSelectionRange()
- 关于js中出现获取input框的值为[object HTMLInputElement]的问题
- jquery实现点击input选中文字代码
- Failed to set the 'value' property on 'HTMLInputElement': This input element accepts a filename,...
- Failed to set the 'value' property on 'HTMLInputElement': This input element解决办法
- setSelectionRange()函数-只支持Firefox浏览器-设置文本框某段文字的光标选中
- JS获取DropDownList 选中值的value
- jQuery控制input的value值,代码中有值,但是页面中不能显示的原因
- Jquery 获取select 选中的值 input radio 是否选中
- JS遍历被选中input的值
- 如何获取input radio选中的值。
- 获取选中行的input值
- input的value值在页面上被改变,但是查看器代码中值不改变
- input value="值栈的值"
- input的value注意
- JavaScript 选择input光标所在位置 设置input的内容选中并得到选中的值
- IFrame 系列3 ---- js选中文字API: setSelectionRange跟createTextRange
- input radio 选中的操作
- servlet如何判断是哪个表单传来的数据???
- Centos配置ssh免密码互信登录
- Codeforces Round #442 (Div. 2)【solved : 6 / 6】
- selenium自动化(一)
- 基于GitHub搭建Hexo静态博客
- 代码实现input的value值选中HTMLInputElement.setSelectionRange()
- 字典序全排列
- JavaScript原型——构造函数
- 1014. 福尔摩斯的约会 (20)
- Node.js 异常处理
- 【Unity】基于矩阵的UGUI引导蒙版方案
- 如何把一个基于Maven项目所有的jar文件快速列出到Excel?
- js前端抓取网页图标
- 新版Hbase API 用法示例