是否可以获取页面中选中文本的父元素?例如:
<div class="someparent">
Selection of this text should refer to the 'someparent' class.
<span class="spanparent">If this is selected, the parent should be this span</span>
</div>
因为在获取选中文本的时候,一般是从窗口或者文档中获取(取决于浏览器)但是有没有可能获取到选中文本的父元素呢?
最佳答案
这是一个函数,可以让您获得包含所有主要浏览器中全部用户选择的最内层元素(选择多个范围时除外,这仅在 Firefox 中受支持。如果这很重要,我可以扩展示例也处理这种情况):
function getSelectionParentElement() {
var parentEl = null, sel;
if (window.getSelection) {
sel = window.getSelection();
if (sel.rangeCount) {
parentEl = sel.getRangeAt(0).commonAncestorContainer;
if (parentEl.nodeType != 1) {
parentEl = parentEl.parentNode;
}
}
} else if ( (sel = document.selection) && sel.type != "Control") {
parentEl = sel.createRange().parentElement();
}
return parentEl;
}
关于javascript - 获取选定文本的父元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7215479/