$('div').click( function () {
getSelectionPosition ();
});
function getSelectionPosition () {
var selection = window.getSelection();
console.log(selection.focusNode.data[selection.focusOffset]);
alert(selection.focusOffset);
}
This works with "click", as well as with a "range" for most browsers. (selection.type = "caret"
/ selection.type = "range"
).
selection.focusOffset()
gives you the position in the inner node. If elements are nested, within <b>
or <span>
tags for example, it will give you the position inside the inner element, not the full text, more or less. I'm unable to "select" the first letter of a sub tag with focusOffset
and "caret" type (click, not range select). When you click on the first letter, it gives the position of the last element before the start of tag plus 1. When you click on the second letter, it correctly gives you "1". But I didn't find a way to access the first element (offset 0) of the sub element. This "selection/range" stuff seems buggy (or very non-intuitive to me). ^^
But it's quite simple to use without nested elements! (Works fine with your <div>
)
Here is a fiddle
Important edit 2015-01-18:
This answer worked back when it was accepted, but not anymore, for reasons given below. Other answers are now most useful.
- Matthew's general answer
- The working example provided by Douglas Daseeco.
Both Firefox and Chrome debugged window.getSelection()
behavior. Sadly, it is now useless for this use case. (Reading documentation, IE 9 and beyond shall behave the same).
Now, the middle of a character is used to decide the offset. That means that clicking on a character can give back 2 results. 0 or 1 for the first character, 1 or 2 for second, etc.
I updated the JSFiddle example.
Please note that if you resize the window (Ctrl + mouse), the behavior is quite buggy on Chrome for some clicks.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…