欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

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

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

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

一、navigator.clipboard 對(duì)象

1. navigator.clipboard 方法匯總

方法用途
Clipboard.readText()復(fù)制剪貼板里的文本數(shù)據(jù)
Clipboard.read()復(fù)制剪貼板里的文本數(shù)據(jù)/二進(jìn)制數(shù)據(jù)
Clipboard.writeText()將文本內(nèi)容寫入剪貼板
Clipboard.write()將文本數(shù)據(jù)/二進(jìn)制數(shù)據(jù)寫入剪貼板

2. 代碼示例

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

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

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

Clipboard.write()不僅在剪貼板可寫入普通text,還可以寫入圖片數(shù)據(jù)(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)缺點(diǎn)

① 優(yōu)點(diǎn)

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

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

② 缺點(diǎn): 允許腳本任意讀取會(huì)產(chǎn)生安全風(fēng)險(xiǎn),安全限制較多。

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

調(diào)用時(shí)需要明確獲得用戶的許可。

二、document.execCommand() 方法

1. document.execCommand() 方法匯總

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

2. 代碼示例

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

結(jié)合 window.getSelection()方法實(shí)現(xiàn)一鍵復(fù)制功能:

    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)缺點(diǎn)

① 優(yōu)點(diǎn)

使用方便;

各種瀏覽器都支持;

② 缺點(diǎn)

只能將選中的內(nèi)容復(fù)制到剪貼板;

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

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

您可能感興趣的文章:

相關(guān)文章

最新評(píng)論