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

前端 未结 1 1239
别跟我提以往
别跟我提以往 2020-12-13 22:22

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


        
相关标签:
1条回答
  • 2020-12-13 23:12

    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);
    
    0 讨论(0)
提交回复
热议问题