Get caret position using jCaret Plugin in IE
I开发者_如何学运维 have problem with jCaret plugin in IE.
jCaret downloads
I want to get the caret position inside a textarea.
My code looks like this:
$('.myTextArea').click(function(){
var myCaretPos = $(this).caret().end;
});
The problem in IE is that I only get correct result if the textarea is only one line, but if there are more than one line the result is wrong. It seems that line breaks takes one extra char in IE. So how can I remove line breaks in IE?
I've encountered and solved this problem. Here's a function that will do it outside jQuery:
function getInputSelection(el) {
var start = 0, end = 0, normalizedValue, range,
textInputRange, len, endRange;
if (typeof el.selectionStart == "number" && typeof el.selectionEnd == "number") {
start = el.selectionStart;
end = el.selectionEnd;
} else {
range = document.selection.createRange();
if (range && range.parentElement() == el) {
len = el.value.length;
normalizedValue = el.value.replace(/\r\n/g, "\n");
// Create a working TextRange that lives only in the input
textInputRange = el.createTextRange();
textInputRange.moveToBookmark(range.getBookmark());
// Check if the start and end of the selection are at the very end
// of the input, since moveStart/moveEnd doesn't return what we want
// in those cases
endRange = el.createTextRange();
endRange.collapse(false);
if (textInputRange.compareEndPoints("StartToEnd", endRange) > -1) {
start = end = len;
} else {
start = -textInputRange.moveStart("character", -len);
start += normalizedValue.slice(0, start).split("\n").length - 1;
if (textInputRange.compareEndPoints("EndToEnd", endRange) > -1) {
end = len;
} else {
end = -textInputRange.moveEnd("character", -len);
end += normalizedValue.slice(0, end).split("\n").length - 1;
}
}
}
}
return {
start: start,
end: end
};
}
And an example of how to use it:
$('.myTextArea').click(function(){
var myCaretPos = getInputSelection(this).end;
});
I've also made a jQuery plug-in that includes this functionality, along with other functionality relating to textarea selections. It's not yet released but is stable and tested. Source is here: http://code.google.com/p/rangy/source/browse/trunk/src/js/modules/textinputs_jquery.js. Example:
$('.myTextArea').click(function(){
var myCaretPos = $(this).getSelection().end;
});
精彩评论