我即将实施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