JavaScript如何获取选区的偏移量?

场景出现在一个富文本编辑器种,我要选中一段文本,选中之后在选中的文本中间上方出现一个tooltips

不清楚应该使用哪种方法获取一个selection(选区)的起始点和结束点相较于body的偏移量(不是字符偏移量),从而定位tooltips元素。

阅读 3.5k
2 个回答
const 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;
};

const getSelectionRect = selection => {
  if (selection.rangeCount <= 0) {
    return null;
  }

  const _rect = selection.getRangeAt(0).getBoundingClientRect();
  let rect = _rect && _rect.top ? _rect : selection.getRangeAt(0).getClientRects()[0];
  if (!rect) {
    if (selection.anchorNode && selection.anchorNode.getBoundingClientRect) {
      rect = selection.anchorNode.getBoundingClientRect();
    } else {
      return null;
    }
  }
  return rect;
};

// 获取选择
const selection = getSelection(window);
// 获取选择区域边界
const selectionRect = getSelectionRect(selection);
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题