如何使用javascript document.getSelecttion()在html中获取所选文本的坐标 [英] how do I get co-ordinates of selected text in an html using javascript document.getSelecttion()

查看:642
本文介绍了如何使用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);

这篇关于如何使用javascript document.getSelecttion()在html中获取所选文本的坐标的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆