js點擊按鈕複製內容到粘貼板

複製內容到粘貼板,就是要選擇須要複製的內容並執行document.execCommand("copy")命令:app

//複製內容到粘貼板
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等)須要複製內容,能夠寫一個通用方法:spa

//複製內容到粘貼板
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;
}
相關文章
相關標籤/搜索