简体   繁体   English

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

[英]how do I get co-ordinates of selected text in an html using javascript document.getSelecttion()

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

Example: (image) 示例:(图片)

替代文字

Here is the basic idea. 这是基本思想。 You insert dummy element in the beginning of the selection and get the coordinates of that dummy html element. 您可以在选择的开头插入虚拟元素,并获取该虚拟html元素的坐标。 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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM