سؤال

I have a label and am setting ondblclick on it:

<label ondblclick="foo(event);" 
 style="white-space: pre; font-family: Monospace; font-size: 12px;">
lot's of text here blah blah blah and more...

I get the callback to a Javascript function when doubleclicking a word in the text.

I want to know how many characters into the text the selection is.

I can get the selection itself using something like:

(window.getSelection && window.getSelection().toString())

and of course I have the textnode itself so I have the text as a whole.

But the selection can appear many times in the text node -- I need to know the offset from a character perspective. For example, if the user double clicks on blah I want to know which one it was.

All I can find in the event are various X,Y coordinates which look like pixels to me -- but I have two scroll bars, formatting etc, so computing the character offset from pixels will be very very difficult.

Is this information somewhere in the event data or is there code for computing this somehow?

Any help greatly appreciated.

هل كانت مفيدة؟

المحلول

If selections start within the label node, the object returned by window.getSelection() should have an anchorOffset property which gives you what you want.

window.getSelection().anchorOffset

I am not sure about cross-browser-compatibility, though. For an example, see this JSFiddle:

http://jsfiddle.net/Lx5D2/

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top