鍍金池/ 問答/HTML/ JavaScript如何獲取選區(qū)的偏移量?

JavaScript如何獲取選區(qū)的偏移量?

場景出現(xiàn)在一個富文本編輯器種,我要選中一段文本,選中之后在選中的文本中間上方出現(xiàn)一個tooltips

不清楚應該使用哪種方法獲取一個selection(選區(qū))的起始點和結(jié)束點相較于body的偏移量(不是字符偏移量),從而定位tooltips元素。

回答
編輯回答
純妹

$(selector).offset()

2017年4月6日 22:57
編輯回答
嫑吢丕
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);
// 獲取選擇區(qū)域邊界
const selectionRect = getSelectionRect(selection);
2017年10月10日 01:13