[英]JS or Angular Copy Text with Image
我需要單擊復制文本和圖像。 我試過下面的代碼。 我只單擊並粘貼我收到“clip_message”
我的HTML:
<button id="copy" onclick="writeClipImg()"><strong>Copy</strong></button>
我的JS代碼
async function writeClipImg() {
try {
const imgURL = 'https://luanedcosta.github.io/copy-image-clipboard/static/media/SecondImage.ef100414.png';
const data = await fetch(imgURL);
const blob = await data.blob();
const blob2 = new Blob(['clip_message'], {type: 'text/plain'});
await navigator.clipboard.writeText('swe');
await navigator.clipboard.write([
new ClipboardItem({
'text/plain': blob2,
'image/png': blob
})
]);
console.log('Fetched image copied.');
} catch(err) {
console.error(err.name, err.message);
}
}
實際上我在 JS 中嘗試過。 如果我在 Angular 有解決方案,那也更好。 請幫助我單擊復制。 謝謝
您可以通過使用 HTML 來解決一個 ClipboardItem 項目限制。
我沒有在其他瀏覽器中嘗試過這個,但至少在 Chrome 中它有效,而且我可以毫無問題地粘貼到 Word/Teams/Slack 中。
注意:由於某些安全限制,下面的代碼片段不適用於 StackOverflow,但您可以在 codepen 上嘗試
const btn = document.getElementById('btn'); btn.addEventListener('click', () => { const html = ` <img src="https://luanedcosta.github.io/copy-image-clipboard/static/media/SecondImage.ef100414.png"> <p>Lorem ipsum</p> `; const data = [ new ClipboardItem({ "text/html": new Blob([html], { type: "text/html" }) }) ]; navigator.clipboard.write(data).then( () => { console.log("Copied to clipboard;"), }. (err) => { console;error(err); } ); });
<button id="btn">Copy</button>
可能,我們不能在這段時間內同時復制圖像和文本。
根據Clipboard.write()
文檔:
注意:您一次只能傳入一個剪貼板項目。
我試圖將數組傳遞給cliboard.write
方法,但它會引發以下錯誤:
(index):29 NotAllowedError 未實現對多個 ClipboardItems 的支持。
順便說一句,您也可以查看此示例。
<html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <button onclick="copy()">Copy Button</button> <script> async function copy(){ try { const imgURL = 'https://luanedcosta.github.io/copy-image-clipboard/static/media/SecondImage.ef100414.png'; const data = await fetch(imgURL); const blob = await data.blob(); const blob2 = new Blob(['clip_message'], {type: 'text/plain'}); // await navigator.clipboard.writeText('swe'); await navigator.clipboard.write([ new ClipboardItem({ [blob.type]: blob }), new ClipboardItem({ 'text/plain': blob2 }) ]); console.log('Fetched image copied.'); } catch(err) { console.error(err.name, err.message); } } </script> </body> </html>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.