[前端] 定位光标位置
2015-09-29 11:17
549 查看
当input框获取焦点的时候,改变光标的位置
谢谢关注!
方法一:
function setSelectionRange(input, selectionStart, selectionEnd) { if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } else if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } } function setCaretToPos (input, pos) { setSelectionRange(input, pos, pos); } // 调用 setCaretToPos(document.getElementById("input"), 4);
方法二:
$.fn.selectRange = function(start, end) { return this.each(function() { if (this.setSelectionRange) { this.focus(); this.setSelectionRange(start, end); } else if (this.createTextRange) { var range = this.createTextRange(); range.collapse(true); range.moveEnd('character', end); range.moveStart('character', start); range.select(); } }); }; // 调用 $('#ele').selectRange(3,5);
方法三:
$.fn.setCursorPosition = function(position){ if(this.lengh == 0) return this; return $(this).setSelection(position, position); } $.fn.setSelection = function(selectionStart, selectionEnd) { if(this.lengh == 0) return this; input = this[0]; if (input.createTextRange) { var range = input.createTextRange(); range.collapse(true); range.moveEnd('character', selectionEnd); range.moveStart('character', selectionStart); range.select(); } else if (input.setSelectionRange) { input.focus(); input.setSelectionRange(selectionStart, selectionEnd); } return this; } $.fn.focusEnd = function(){ this.setCursorPosition(this.val().length); } // 调用 $(ele).focusEnd();
谢谢关注!
相关文章推荐
- JS Map 和 List 的简单实现代码
- JavaScript:继承
- JavaScript:instanceof
- json_decode()和json_encode()区别----2015-0929
- js中关于map的增、删、改、查操作及其js中如何建立一个对象
- nodejs模块xml2js解析xml的坑
- nodejs模块xml2js解析xml的坑
- jQuery.validate验证上传文件大小
- AngularJS 官方案例:angular-phonecat
- jQuery自定义插件开发基础1——jQuery实用函数的实现
- Html 的实体字符大全
- jqzoom基于jQuery的图片放大镜
- hibernate json数据死循环
- 使用CSS3的::selection改变选中文本颜色的方法
- Web前端持续集成方案(一)
- HTML5 in Drupal 7
- Nodejs学习<1>
- C++ JsonCpp 使用(完整代码下载)
- FlatBuffers的使用
- 【HTML】-案例-利用表格制作网页