I'm working on a custom tokenfield based on textarea. The idea is to have a textarea with div elements absolutely positioned above, so it looks like they are in text area.
It was pain so far, but I managed to do pretty much everything, except one thing.
Is it even possible in javascript to set reverse-selection? When you put a cursor somewhere in the middle of textarea, hold down shift and press left arrow a few times, you'll get a 开发者_如何学编程selection. The tricky part, is that it's not usual - it's backwards (it's start is to the right from the end, not like it is usually). There are placeholders in my textarea over which I display my divs (tokens). When you navigate to one of them, cursor jumps to the opposite edge of a placeholder, so it feels natural. When you hold down shift, and reach the placeholder, it jumps to the right, and it sets a new selection, so it looks like you selected the token (you can press delete, and remove selected range with token itself, which is cool). BUT it wont possibly work if you navigate from right to left, because setting a new selection would make it unreverted one:
Left-to-right selection:
abcde[start]efg[end](token)
[shift]+[right]
abcde[start]efg(token)[end]
[del]
abcde
Right-to-left selection
(token)[end]efg[start]abcde
[shift]+[left]
[start](token)abcdeefg[end] //see? it's back to normal
[shift]+[left]
[start](token)abcdeef[end]g //huh?! shift-right moves end point (unexpected)
abcde
So here's question: Can I set a selection in textarea where start point would be greater than the end point? Simply element.setSelectionRange(right, left)
does not work in firefox, any other ideas?
After experimenting a bit in the Firebug console, I think it is not trivial. However, you can intercept the keypress event:
If the user presses the left arrow, you have to extend the selection to the left yourself and return false
. Then the browser's default is not called, but the user has nevertheless the feeling of a leftwards selection.
textarea.onkeypress = function (event) {
if (!event){event = window.event; /* %#$! IE */ }
if (event.shiftKey && event.keyCode == 37 /* left */) {
event.target.selectionStart = currentSelectionStart - 1;
}
return false;
};
37 is the left arrow, 38 is up, 39 is right and 40 is down.
精彩评论