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 關注
- 991 瀏覽
添加回答
舉報
0/150
提交
取消
