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

痞子三分冷 提交于 2019-11-30 06:28:54

问题


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)


回答1:


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


来源:https://stackoverflow.com/questions/2605133/how-do-i-get-co-ordinates-of-selected-text-in-an-html-using-javascript-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!