輕松實現js復制內容和修改粘貼板中內容


實現點擊不是input或者texterea框的時候復制功能,需求有時復制按鈕需要放置一些特殊的內容,比如一個選中的樹節點,如果需要獲取到它的id的時候,還有可能會讓你在粘貼前對id進行判斷,如果已經存在亦或者是根節點等特殊情況再次做操作的情況。

主要通過以下兩個API 進行實現,兼容性可以點擊鏈接查看。

當一個HTML文檔切換到設計模式時,document暴露 execCommand 方法,該方法允許運行命令來操縱可編輯內容區域的元素。(摘自MDN)

是可編輯區域可被操縱。所以需要創建一個臨時的input框或者textarea,如果內容需要保存格式時使用textarea

execCommand

execCommand兼容性

const btn = document.querySelector("#btn");
btn.addEventListener("click", function() {
    // 創建一個input框
    const input = document.createElement("input");
    // 設置 input框內容
    input.setAttribute("value", "copy content");
    // 添加到body元素中
    document.body.appendChild(input);

    // 將新添加進去的input元素進行選中
    input.select();

    // 為input添加監聽事件方便對剪貼板內容進行二次修改
    input.addEventListener("copy", function(event) {
        // 使用ClipboardApi來設置剪貼板里的內容
        // 參考張鑫旭的博客, 需要的文末有地址
        var clipboardData = event.clipboardData || window.clipboardData;
        if (!clipboardData) {
            return;
        }
        var text = window.getSelection().toString();
        if (text) {
            event.preventDefault();
            clipboardData.setData("text/plain", text + "\n\n 我是添加進來的內容");
        }
    });

    // 執行復制操作
    if (document.execCommand("copy")) {
        console.log("復制成功");
    } else {
        console.log("復制失敗");
    }

    // document.execCommand('copy') 如果內容復制的不全
    // document.execCommand('copy')前先進行document.execCommand('selectAll')選中所有內容即可

    // 移除input框
    document.body.removeChild(input);
});

張鑫旭博客


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM