将光标定位于输入框最右侧的实现方式
2016-03-29 15:38
246 查看
这个方法setCursorPosition需要使用两个原生API
setSelectionRange
createTextRange
Source:
http://www.uncletoo.com/html/jsjquery/755.html http://www.cnblogs.com/snandy/p/4112488.html
setSelectionRange
createTextRange
<html> <head> <title></title> <script src="./js/jquery-2.2.2.min.js"></script> </head> <body> <input type="text" id="test" /> <script> (function($, undefined) { $.fn.getCursorPosition = function() { var el = $(this).get(0); var pos = 0; if ('selectionStart' in el) { pos = el.selectionStart; } else if ('selection' in document) { el.focus(); var Sel = document.selection.createRange(); var SelLength = document.selection.createRange().text.length; Sel.moveStart('character', -el.value.length); pos = Sel.text.length - SelLength; } return pos; }; $.fn.setCursorPosition = function(option) { var settings = $.extend({ index: 0 }, option); return this.each(function() { var elem = this; var val = elem.value; var len = val.length; var index = settings.index; // 非input和textarea直接返回 var $elem = $(elem); if (!$elem.is('input,textarea')) { return; } // 超过文本长度直接返回 if (len < index) { return; } setTimeout(function() { elem.focus() if (elem.setSelectionRange) { // 标准浏览器 elem.setSelectionRange(index, index) ; } else { // IE9- var range = elem.createTextRange(); range.moveStart("character", -len); range.moveEnd("character", -len); range.moveStart("character", index); range.moveEnd("character", 0); range.select(); } }, 10); }); }; })(jQuery); $("#test").on("focus", function(){ var pos = $(this).getCursorPosition(); $(this).setCursorPosition({index:$(this).val().length}); }); </script> </body> </html>
Source:
http://www.uncletoo.com/html/jsjquery/755.html http://www.cnblogs.com/snandy/p/4112488.html
相关文章推荐
- Html5之高级-5 HTML5音频处理(在H5中播放音频、编程实现音频播放器)
- js滚动条平滑移动示例代码
- backBarButtonItem去除title 修改图片 换颜色
- 键盘工具栏的快速集成--IQKeyboardManager
- C/C++中const关键字详解
- hdu5651xiaoxin juju needs help 乘法的逆元||重复元素的排列
- mongodb Failed: error connecting to db server: no reachable servers
- 机器学习 深度学习 计算机视觉 资料汇总
- Filter --- 使用URL Rewrite实现伪静态网站
- Hibernate 缓存机制
- 《oracle每日一练》oralce数据库的导入导出
- 智能指针之第二印象
- MySQL应用层传输协议分析
- 完整java开发中JDBC连接数据库代码和步骤
- Linux下搭建java环境
- 70. Climbing Stairs
- iOS 重写pop跳转的方法
- BZOJ 4184 shallot
- 自定义可折叠和展开的View
- 如何实现监听Android输入法弹出收回,为什么要使用接口