用JQuery获取输入框中的光标位置

来源:互联网 发布:软件测试 阶段 编辑:程序博客网 时间:2024/06/12 01:17

1.js代码

(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;        }    })(jQuery);

2、调用

$('#id').getCursorPosition();