你可以使用一个TreeWalker
使用document.createTreeWalker
.一个例子如下.它列出了部分或全部选中的所有元素.您可以通过修改传递给的参数轻松更改行为document.createTreeWalker
.
请注意,在Firefox中,您无需检查是否存在getRangeAt
选择方法.只有旧版本的WebKit才需要进行此检查.此外,IE <9不支持TreeWalker或Range,因此以下内容在这些浏览器中不起作用.
根据以下评论编辑固定.
function rangeIntersectsNode(range, node) { var nodeRange; if (range.intersectsNode) { return range.intersectsNode(node); } else { nodeRange = node.ownerDocument.createRange(); try { nodeRange.selectNode(node); } catch (e) { nodeRange.selectNodeContents(node); } return range.compareBoundaryPoints(Range.END_TO_START, nodeRange) == -1 && range.compareBoundaryPoints(Range.START_TO_END, nodeRange) == 1; } } function getSelectedElementTags(win) { var range, sel, elmlist, treeWalker, containerElement; sel = win.getSelection(); if (sel.rangeCount > 0) { range = sel.getRangeAt(0); } if (range) { containerElement = range.commonAncestorContainer; if (containerElement.nodeType != 1) { containerElement = containerElement.parentNode; } treeWalker = win.document.createTreeWalker( containerElement, NodeFilter.SHOW_ELEMENT, function(node) { return rangeIntersectsNode(range, node) ? NodeFilter.FILTER_ACCEPT : NodeFilter.FILTER_REJECT; }, false ); elmlist = [treeWalker.currentNode]; while (treeWalker.nextNode()) { elmlist.push(treeWalker.currentNode); } console.log(elmlist); } }