1. 程式人生 > >前端實現複製貼上

前端實現複製貼上

//複製到剪下板
function copyToClipboard(elem) {
    var targetId = "_hiddenCopyText_";
var isInput = elem.tagName === "INPUT" || elem.tagName === "TEXTAREA";
var origSelectionStart, origSelectionEnd;
if (isInput) {
        // 如果是input標籤或textarea,則直接指定該節點
target = elem;
origSelectionStart = elem.selectionStart
; origSelectionEnd = elem.selectionEnd; } else { // 如果不是,則使用節點的textContent 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"); layer.open({ type: 1, title: false, closeBtn: 1, area:['440px','250px'], skin: 'layui-layer-nobg', //沒有背景色 shadeClose: true, content: $("#copyTip") }); } catch(e) { succeed = false; layer.open({ type: 1, title: false, closeBtn: 1, area:['440px','250px'], skin: 'layui-layer-nobg', //沒有背景色 shadeClose: true, content: $("#copyErrTip") }); } // 不再聚焦 if (currentFocus && typeof currentFocus.focus === "function") { currentFocus.focus(); } if (isInput) { // 清空臨時資料 elem.setSelectionRange(origSelectionStart, origSelectionEnd); } else { // 清空臨時資料 target.textContent = ""; } return succeed; } $("#copy").on('click',function(){ var copytxt=document.querySelector('#copy'); copyToClipboard(copytxt); });