textarea中的光标位置(字符索引,而不是x / y坐标)如何使用jQuery在textarea中获得插入符号的位置?我正在寻找光标从文本开头的偏移,而不是(x,y)位置。
3 回答
达令说
TA贡献1821条经验 获得超6个赞
不是jQuery,而只是Javascript ......
var position = window.getSelection().getRangeAt(0).startOffset;
GCT1015
TA贡献1827条经验 获得超4个赞
修改了BojanG的解决方案以使用jQuery。在Chrome,FF和IE中测试过。
(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);基本上,要在文本框中使用它,请执行以下操作:
$("#myTextBoxSelector").getCursorPosition();- 3 回答
- 0 关注
- 1005 浏览
添加回答
举报
0/150
提交
取消
