gpt4 book ai didi

javascript - 如何将网址转换为图片?

转载 作者:行者123 更新时间:2023-11-28 02:43:48 25 4
gpt4 key购买 nike

我目前正在使用下面的代码来检测一个 URL 是否被粘贴到一个 contenteditable div 中。如果粘贴 URL,它将自动转换为链接(由 a 标记包围)。

我该如何更改它,以便如果用户粘贴图像 URL,它将转换为 <img src="https://example.com/image.jpg">同时还将非图像 URL 转换为标准链接(由 a 标记包围)。

var saveSelection, restoreSelection;

if (window.getSelection && document.createRange) {
saveSelection = function(containerEl) {
var range = window.getSelection().getRangeAt(0);
var preSelectionRange = range.cloneRange();
preSelectionRange.selectNodeContents(containerEl);
preSelectionRange.setEnd(range.startContainer, range.startOffset);
var start = preSelectionRange.toString().length;

return {
start: start,
end: start + range.toString().length
}
};


} else if (document.selection) {

}

function createLink(matchedTextNode) {
var el = document.createElement("a");
el.href = matchedTextNode.data;
el.appendChild(matchedTextNode);
return el;
}

function shouldLinkifyContents(el) {
return el.tagName != "A";
}

function surroundInElement(el, regex, surrounderCreateFunc, shouldSurroundFunc) {
var child = el.lastChild;
while (child) {
if (child.nodeType == 1 && shouldSurroundFunc(el)) {
surroundInElement(child, regex, createLink, shouldSurroundFunc);
} else if (child.nodeType == 3) {
surroundMatchingText(child, regex, surrounderCreateFunc);
}
child = child.previousSibling;
}
}

function surroundMatchingText(textNode, regex, surrounderCreateFunc) {
var parent = textNode.parentNode;
var result, surroundingNode, matchedTextNode, matchLength, matchedText;
while ( textNode && (result = regex.exec(textNode.data)) ) {
matchedTextNode = textNode.splitText(result.index);
matchedText = result[0];
matchLength = matchedText.length;
textNode = (matchedTextNode.length > matchLength) ?
matchedTextNode.splitText(matchLength) : null;
surroundingNode = surrounderCreateFunc(matchedTextNode.cloneNode(true));
parent.insertBefore(surroundingNode, matchedTextNode);
parent.removeChild(matchedTextNode);
}
}

var textbox = $('.editable')[0];
var urlRegex = /http(s?):\/\/($|[^\s]+)/;

function updateLinks() {
var savedSelection = saveSelection(textbox);
surroundInElement(textbox, urlRegex, createLink, shouldLinkifyContents);
restoreSelection(textbox, savedSelection);
}

var $textbox = $(textbox);

$(document).ready(function () {
$textbox.focus();

var keyTimer = null, keyDelay = 1000;

$textbox.keyup(function() {
if (keyTimer) {
window.clearTimeout(keyTimer);
}
keyTimer = window.setTimeout(function() {
updateLinks();
keyTimer = null;
}, keyDelay);
});
});

最佳答案

您是否尝试解析粘贴的 url,并搜索结尾扩展名(jpg、gif、png)?

它应该很简单,如果结尾匹配其中之一,那么您将 url 包装到一个 href propriety 中。

这段代码是你自己写的吗?

在这里您可以阅读有关执行此操作的字符串方法:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String

关于javascript - 如何将网址转换为图片?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42422738/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com