您好,登錄后才能下訂單哦!
本篇內(nèi)容主要講解“vue怎么實現(xiàn)復(fù)制文字和圖片”,感興趣的朋友不妨來看看。本文介紹的方法操作簡單快捷,實用性強。下面就讓小編來帶大家學(xué)習(xí)“vue怎么實現(xiàn)復(fù)制文字和圖片”吧!
在很久之前我們是使用document.execCommand('copy')來實現(xiàn)復(fù)制文本的,但是現(xiàn)在mdn上已經(jīng)將這個命令廢棄了。
當一個 HTML 文檔切換到設(shè)計模式時,document
暴露 execCommand
方法,該方法允許運行命令來操縱可編輯內(nèi)容區(qū)域的元素。如果傳入copy命令,那么就能實現(xiàn)復(fù)制的功能。
比如像下面這樣
// 復(fù)制文字 copyText(link, cb) { let input = document.createElement('textarea'); input.style.cssText = 'position: absolute; top: 0; left: 0; opacity: 0; z-index: -10;'; input.value = link; document.body.appendChild(input); input.select(); document.execCommand('copy'); document.body.removeChild(input); if (typeof cb === 'function') { cb(); } }
Clipboard
接口實現(xiàn)了 Clipboard API,如果用戶授予了相應(yīng)的權(quán)限,其就能提供系統(tǒng)剪貼板的讀寫訪問能力。在 Web 應(yīng)用程序中,Clipboard API 可用于實現(xiàn)剪切、復(fù)制和粘貼功能。
Clipboard提供了以下方法,方便我們讀取剪切板的內(nèi)容。
read():從剪貼板讀取數(shù)據(jù)(比如圖片),返回一個 Promise
對象。在檢索到數(shù)據(jù)后,promise 將兌現(xiàn)一個 ClipboardItem
對象的數(shù)組來提供剪切板數(shù)據(jù)。
readText():從操作系統(tǒng)讀取文本;返回一個 Promise
,在從剪切板中檢索到文本后,promise 將兌現(xiàn)一個包含剪切板文本數(shù)據(jù)的 DOMString
。
write(): 寫入任意數(shù)據(jù)至操作系統(tǒng)剪貼板。這是一個異步操作,在操作完成后,返回的 promise 的將被兌現(xiàn)。
writeText(): 寫入文本至操作系統(tǒng)剪貼板。返回一個 Promise
,在文本被完全寫入剪切板后,返回的 promise 將被兌現(xiàn)。
復(fù)制文本的方法很簡單,就是使用navigator.clipboard.writeText()
方法。
具體代碼實現(xiàn)如下:
copyTextToClipboard(text) { return new Promise((resolve, reject) => { navigator.clipboard.writeText(text).then( () => { resolve(true) }, () => { reject(new Error('復(fù)制失敗')) } ) }) }
復(fù)制圖片主要用到navigator.clipboard.write()方法。 因為我們在頁面中通常是要根據(jù)一個img元素復(fù)制圖片,主要實現(xiàn)思路如下:
先將img元素
轉(zhuǎn)成base64
再將base64
轉(zhuǎn)成blob對象
根據(jù)blob對象
new一個ClipboardItem
對象
最后再根據(jù)navigator.clipboard.writeText()
將內(nèi)容寫入剪貼板中
具體代碼實現(xiàn)如下:
// 圖片元素轉(zhuǎn)base64 getBase64Image(img) { let canvas = document.createElement('canvas'); canvas.width = img.width; canvas.height = img.height; let ctx = canvas.getContext('2d'); ctx?.drawImage(img, 0, 0, img.width, img.height); let dataURL = canvas.toDataURL('image/png'); return dataURL; }, // base64圖片轉(zhuǎn)為blob getBlobImage(dataurl) { let arr = dataurl.split(','); let mime = arr[0].match(/:(.*?);/)[1]; let bstr = atob(arr[1]); let n = bstr.length; let u8arr = new Uint8Array(n); while (n--) { u8arr[n] = bstr.charCodeAt(n); } return new Blob([u8arr], { type: mime }); }, // 復(fù)制圖片 copyImage(dom, cb) { let dataurl = this.getBase64Image(dom); let blob = this.getBlobImage(dataurl); navigator.clipboard.write([ new window.ClipboardItem({ [blob.type]: blob }) ]).then(function() { if (typeof cb === 'function') { cb(); } }, function() { console.log('圖片復(fù)制失??!'); }); }
到此,相信大家對“vue怎么實現(xiàn)復(fù)制文字和圖片”有了更深的了解,不妨來實際操作一番吧!這里是億速云網(wǎng)站,更多相關(guān)內(nèi)容可以進入相關(guān)頻道進行查詢,關(guān)注我們,繼續(xù)學(xué)習(xí)!
免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。