js點擊按鈕復制內容到粘貼板


復制內容到粘貼板,就是要選擇需要復制的內容並執行document.execCommand("copy")命令:

//復制內容到粘貼板
function copyToClipboard(elemId) {
    var target = document.getElementById(elemId);
    // 選擇內容
    target.focus();
    target.setSelectionRange(0, target.value.length);
    // 復制內容
    var succeed;
    try {
        succeed = document.execCommand("copy");
    } catch (e) {
        succeed = false;
    }
    console.log("復制成功");
    return succeed;
}

如果應用場景復雜些,可能有多種元素(textarea、input、div等)需要復制內容,可以寫一個通用方法:

//復制內容到粘貼板
function copyToClipboard(elemId) {
    var elem = document.getElementById(elemId);
    var targetId = "_hiddenCopyText_";
    var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
    var origSelectionStart, origSelectionEnd;
    if (isInput) {
        // 復制選擇內容
        target = elem;
        origSelectionStart = elem.selectionStart;
        origSelectionEnd = elem.selectionEnd;
    } else {
        // 必須有一個臨時的元素存儲復制的內容
        target = document.getElementById(targetId);
        if (!target) {
            var target = document.createElement("textarea");
            target.style.position = "absolute";
            target.style.left = "-9999px";
            target.style.top = "0";
            target.id = targetId;
            document.body.appendChild(target);
        }
        target.textContent = elem.textContent;
    }
    // 選擇內容
    var currentFocus = document.activeElement;
    target.focus();
    target.setSelectionRange(0, target.value.length);
    // 復制內容
    var succeed;
    try {
        succeed = document.execCommand("copy");
    } catch (e) {
        succeed = false;
    }
    // 恢復焦點
    if (currentFocus && typeof currentFocus.focus === "function") {
        currentFocus.focus();
    }
    if (isInput) {
        // 恢復之前的選擇
        elem.setSelectionRange(origSelectionStart, origSelectionEnd);
    } else {
        // 清除臨時內容
        target.textContent = "";
    }
    console.log("復制成功");
    return succeed;
}

 


免責聲明!

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



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