Skip to content
On this page

通过鼠标选中获取页面 Dom

关键点在于 :Window 对象下的 getSelection 以及 getRangeAt 两个方法,Mdn上有介绍,可以看看

js
const selection = window.getSelection();
const range = selection.getRangeAt(0);
const allWithinRangeParent = range.commonAncestorContainer.getElementsByTagName("*");

const allSelected = [];
for (let i=0, el; el = allWithinRangeParent[i]; i++) {
  if (selection.containsNode(el, true) ) {
    allSelected.push(el);
  }
}

console.log('All selected =', allSelected);

Released under the MIT License.