如果您只想获取“a”标签中的链接,您可以执行以下操作:
function getLinksFromSelection() {
if (window.getSelection) {
var selection = window.getSelection();
if (selection.rangeCount > 0) {
var range = selection.getRangeAt(0);
var div = document.createElement('DIV');
div.appendChild(range.cloneContents());
var links = div.getElementsByTagName("A")
for (var i=0; i < links.length; i++) {
console.log(links[i].href);
}
}
}
如果您还想考虑链接中包含的选择(即链接是选择的父节点),那么您将添加如下内容:
var alink = range.commonAncestorContainer;
if (alink.nodeType == 3) {
// if text node then get parent
alink = alink.parentNode;
}
if (alink.tagName === 'A') {
console.log(alink.href)
}
这是小提琴:http: //jsfiddle.net/ESr3C/