通过辅助功能API获取当前所选文本的全局屏幕坐标,可以使用以下方法:
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
const x = rect.left;
const y = rect.top;
const globalX = x + window.scrollX;
const globalY = y + window.scrollY;
return { x: globalX, y: globalY };
function getSelectedTextPosition() {
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const rect = range.getBoundingClientRect();
const x = rect.left;
const y = rect.top;
const globalX = x + window.scrollX;
const globalY = y + window.scrollY;
return { x: globalX, y: globalY };
}
const position = getSelectedTextPosition();
console.log(position.x, position.y);
注意:在使用该方法时,需要确保当前所选文本的范围信息和位置信息已经被正确获取。
领取专属 10元无门槛券
手把手带您无忧上云