亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

JavaScript實現(xiàn)一鍵復制文本功能的示例代碼

 更新時間:2023年03月21日 15:08:42   作者:藍瑟  
這篇文章主要為大家介紹兩種javascript實現(xiàn)文本復制(將文本寫入剪貼板)的方法,文中的示例代碼講解詳細,大家可以根據需求特點選用

最近小編做了一鍵復制文本的需求(功能如下圖所示)。本文簡單介紹兩種javascript實現(xiàn)文本復制(將文本寫入剪貼板)的方法——navigator.clipboarddocument.execCommand(),大家可以根據需求特點選用。

一、navigator.clipboard 對象

1. navigator.clipboard 方法匯總

方法用途
Clipboard.readText()復制剪貼板里的文本數據
Clipboard.read()復制剪貼板里的文本數據/二進制數據
Clipboard.writeText()將文本內容寫入剪貼板
Clipboard.write()將文本數據/二進制數據寫入剪貼板

2. 代碼示例

方法 1: Clipboard.writeText(), 用于將文本內容寫入剪貼板;

    document.body.addEventListener("click", async (e) => {
      await navigator.clipboard.writeText("Yo");
    });

方法 2: Clipboard.write(), 用于將文本數據/二進制數據寫入剪貼板

Clipboard.write()不僅在剪貼板可寫入普通text,還可以寫入圖片數據(Chrome瀏覽器僅支持png格式)。

 async function copy() {
   const image = await fetch("kitten.png");
   const text = new Blob(["Cute sleeping kitten"], { type: "text/plain" });
   const item = new ClipboardItem({
     "text/plain": text,
     "image/png": image,
   });
   await navigator.clipboard.write([item]);
 }

3. 優(yōu)缺點

① 優(yōu)點

所有操作都是異步的,返回 Promise 對象,不會造成頁面卡頓;

無需提前選中內容,可以將任意內容(比如圖片)放入剪貼板;

② 缺點: 允許腳本任意讀取會產生安全風險,安全限制較多。

Chrome 瀏覽器規(guī)定,只有 HTTPS 協(xié)議的頁面才能使用這個 API;

調用時需要明確獲得用戶的許可。

二、document.execCommand() 方法

1. document.execCommand() 方法匯總

方法用途
document.execCommand('copy')復制
document.execCommand('cut')剪切
document.execCommand('paste')粘貼

2. 代碼示例

document.execCommand('copy'),用于將已選中的文本內容寫入剪貼板。

結合 window.getSelection()方法實現(xiàn)一鍵復制功能:

    const TestCopyBox = () => {
    const onClick = async () => {
    const divElement = document.getElementById("select-div");
    if (window.getSelection) {
    const selection = window.getSelection();
    const range = document.createRange();
    range.selectNodeContents(divElement);
    selection.removeAllRanges();
    selection.addRange(range);
    }
    document.execCommand("copy");
    };
    return <div>
     <button onClick={onClick}>copy</button>
     <div id="select-div"> <input /> <span>test2: 3</span><span>test3: 94</span></div>
    </div>
    };

3. 優(yōu)缺點

① 優(yōu)點

使用方便;

各種瀏覽器都支持;

② 缺點

只能將選中的內容復制到剪貼板;

同步操作,如果復制/粘貼大量數據,頁面會出現(xiàn)卡頓。

到此這篇關于JavaScript實現(xiàn)一鍵復制文本功能的示例代碼的文章就介紹到這了,更多相關JavaScript一鍵復制文本內容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!

相關文章

最新評論