我即將實施Facebook在我的contenteditable div集成如果我給'$'和一些像'a'字符我需要一個自動建議應該彈出靠近我的位置。得到最後一個字符在插入符號前插入位置
我需要知道如何在插入位置前找出最後一個字符,無論是在JavaScript中的IE瀏覽器還是其他瀏覽器。我有權訪問Jquery庫。
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
eg.
var caretPosition = $("#contenteditablediv").getCursorPosition();
var lastchar = getchar(caretposition -1);???
該函數將不會在非IE瀏覽器CONTENTEDITABLE元素工作。它用於輸入和textareas。 – 2013-03-01 12:14:05
是的,我知道這只是一個例子..你可以建議我一些其他的方式來找到最後一個字符之前插入位置? – Anoop 2013-03-01 12:17:33