js获取选中文本的第一个字及最后一个字的偏移量

两种方法:
方法一:
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 //坐标是每个字的左上角
            }
        },
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值