是否可以只存储当前所选文字的网址?
这会在页面上保存所选文字
var selectedText = window.getSelection().toString();
这将保存所有超链接
var links = document.links;
编辑:
这将返回null
:
var data=new Object();
data.selectedText = window.getSelection();
console.log(data.selectedText.outerHTML);
答案 0 :(得分:0)
function getLinks() {
var selectedText = window.getSelection().toString();
regex = new RegExp(/((([A-Za-z]{3,9}:(?:\/\/)?)(?:[-;:&=\+\$,\w]+@)?[A-Za-z0-9.-]+|(?:www.|[-;:&=\+\$,\w]+@)[A-Za-z0-9.-]+)((?:\/[\+~%\/.\w-_]*)?\??(?:[-\+=&;%@.\w_]*)#?(?:[\w]*))?)/gim);
var result;
while((result = regex.exec(selectedText)) !== null) {
console.log(result[1])
}
}
答案 1 :(得分:0)
如果您只想获取“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)
}