两种方法:
方法一:
mousedown时获取偏移量,mouseup时获取便宜量就是第一个字及最后一个字的坐标。
方法二:对选中的字画矩形。第一个矩形的坐标就是第一个字的坐标,最后一个字的坐标是x+width,y。
针对方法二给出如下代码:
在mouseup方法中:
var pageDiv=document.getElementById(“id”)//这段文本的id
var selection = that.getSelection(window);
let offsetLeft = that.getAbsLeft(pageDiv);
let offsetTop = that.getAbsTop(pageDiv);
var selectionRect = that.getSelectionRect(selection, offsetLeft, offsetTop);
console.log(selectionRect )
在scoll方法中:that.scrollTop = that.getDocumentScrollTop(document);
在methods中:
getDocumentScrollTop(document) {//页面的滚动高度
var scroll_top = 0;
if (document.documentElement && document.documentElement.scrollTop) {
scroll_top = document.documentElement.scrollTop;
} else if (document.body) {
scroll_top = document.body.scrollTop;
}
return scroll_top;
},
getAbsLeft(obj) {//距离左边的距离
var l = obj.offsetLeft;
while (obj.offsetParent != null) {
obj = obj.offsetParent;
l += obj.offsetLeft;
}
return l;
},
getAbsTop(obj) {//距离顶部的距离
var top = obj.offsetTop;
while (obj.offsetParent != null) {
obj = obj.offsetParent;
top += obj.offsetTop;
}
return top;
},
getSelection(root) {//选中的字获取(主要方法)
let t = null;
if (root.getSelection) {
t = root.getSelection();
} else if (root.document.getSelection) {
t = root.document.getSelection();
} else if (root.document.selection) {
t = root.document.selection.createRange().text;
}
return t;
},
getSelectionRect(selection, offsetLeft, offsetTop) {//获取选中文字的位置(主要方法)。(坐标)
if (selection.rangeCount <= 0) {
return null;
}
if (selection.getRangeAt(0).getClientRects().length > 0) {
let firstRect = selection.getRangeAt(0).getClientRects()[0];//第一个矩形
let lastRect = selection.getRangeAt(0).getClientRects()[selection.getRangeAt(0).getClientRects().length - 1];//最后一个矩形
let firstX = firstRect.x - offsetLeft;//其中offsetLeft是pdf距离左边的距离,offsetTop是pdf距离顶部的距离。
let firstY = firstRect.y + this.scrollTop - offsetTop;//第一个字的纵坐标
let lastX = lastRect.x + lastRect.width - offsetLeft;//最后一个字的横坐标
let lastY = lastRect.y + this.scrollTop - offsetTop;//最后一个字的纵坐标
let coordinate = {
firstX: firstX,
firstY: firstY,
lastX: lastX,
lastY: lastY
}
return coordinate //坐标是每个字的左上角
}
},