我在內容可編輯模式下使用 HTML DIV。從 Javascript 中,給定字串中的有效影像 URL,如何將其轉換為可以推送到剪貼板的內容,以便當我使用 CTRL V 鍵擊粘貼到內容可編輯 DIV 時,它會粘貼影像本身而不是純文本字串?
uj5u.com熱心網友回復:
async function writeClipImg(url) {
try {
const data = await fetch(url);
const blob = await data.blob();
await navigator.clipboard.write([new ClipboardItem({
[blob.type]: blob
})]);
console.log('Fetched image copied.');
} catch (err) {
console.error(err.name, err.message);
}
}
//function from https://developer.mozilla.org/en-US/docs/Web/API/ClipboardItem
let text; //get somehow the text of the div
if (text.indexOf('://') != -1) { //check 'https://' (typic url substring) is there at the text
//only the https care - you can write this for http://, file:///, data etc.
let link = text.slice(text.indexOf('https://'), text.indexOf(' ', text.indexOf('https://')))
//its only get the first link
writeClipImg(link)
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/467688.html
標籤:javascript html 图片 剪贴板 内容可编辑
