最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

firefox - How to get the coordinates of the end of selected text with javascript? - Stack Overflow

programmeradmin0浏览0评论

My problem is similar to this, but I need a way to get the coordinates of the right side of the selection with Javascript in Firefox. I made a small example to show what I mean:

The code I got from the other post is the following:

var range = window.getSelection().getRangeAt(0);
var dummy = document.createElement("span");
range.insertNode(dummy);
var box = document.getBoxObjectFor(dummy);
var x = box.x, y = box.y;
dummy.parentNode.removeChild(dummy);

This gives me the coordinates of the beginning of the selection. Is there any way to retrieve the coordinates of the end of the selection?

My problem is similar to this, but I need a way to get the coordinates of the right side of the selection with Javascript in Firefox. I made a small example to show what I mean:

The code I got from the other post is the following:

var range = window.getSelection().getRangeAt(0);
var dummy = document.createElement("span");
range.insertNode(dummy);
var box = document.getBoxObjectFor(dummy);
var x = box.x, y = box.y;
dummy.parentNode.removeChild(dummy);

This gives me the coordinates of the beginning of the selection. Is there any way to retrieve the coordinates of the end of the selection?

Share Improve this question edited May 23, 2017 at 10:30 CommunityBot 11 silver badge asked Sep 22, 2010 at 8:42 BobBob 1,0291 gold badge10 silver badges12 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 10

Yes. That bit's quite simple: you just need to call collapse(false) on the Range obtained from the selection. Be aware that document.getBoxObjectFor() has now been removed from Mozilla, so you need the dummy element's getBoundingClientRect() method instead:

var range = window.getSelection().getRangeAt(0);
range.collapse(false);
var dummy = document.createElement("span");
range.insertNode(dummy);
var rect = dummy.getBoundingClientRect();
var x = rect.left, y = rect.top;
dummy.parentNode.removeChild(dummy);
var r = range.cloneRange();
r.collapse(false); // collapses range clone to end of original range
r.insertNode(dummy);
// document.getBoxObjectFor(dummy), etc.
发布评论

评论列表(0)

  1. 暂无评论