如何使用javascript document.getSelecttion()在html中获取所选文本的坐标

问题描述:

我想将元素放在选定文本上方。但我无法弄清楚坐标。

I would like to position element above selected text. But I am not able to figure out the coordinates.

var sel = document.getSelection();
  if(sel != null) {
    positionDiv();
}

示例:(图片)

替代文字http://www.freeimagehosting.net/uploads/bf4035f29f.png

这是基本想法。您在选择的开头插入虚拟元素,并获取该虚拟html元素的坐标。然后你删除它。

Here is the basic idea. You insert dummy element in the beginning of the selection and get the coordinates of that dummy html element. Then you remove it.

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);