Get coordinates of beginning and end of a sentence
I have a <span></span>
, within which 开发者_如何转开发a sentence resides. Like:
<span>A sentence residing within a span</span>
Is it possible to get the coordinates of the starting and ending letters of that sentence i.e "A" and "n" respectively on a Javascript event like onmouseover
attached with that span?
The span is resides within a div
. So
case - I: for the sentence
This is a sentence inline
The top and left is evaluated with respect to the letter "T" of the word "This".
case - II: for the sentence
... ... ... ... ... ... This is
a sentence broke into two lines.
The top is evaluated with respect to the letter "T" of the word "This" and the left is evaluated with respect to "a".
Is there any way to get the coordinates of the two terminals of a sentence?
span.getBoundingClientRect()
? docs
If you want the coordinates of the top left of the first character and the bottom right of the last character of the sentence, you can use the getClientRects()
method of the element. It's supported in recent versions of all major browsers.
var rects = span.getClientRects();
var startTopLeft = { x: rects[0].left, y: rects[0].top; };
var lastRect = rects[rects.length - 1];
var endBottomRight = { x: lastRect.right, y: lastRect.bottom; };
Note that these coordinates are relative to the viewport rather than the document. If you need to position other elements using these coordinates, you'll need to account for scrolling.
精彩评论