復制粘貼這個功能我們應該都已經非常熟悉了,但是在特殊情況的時候,需要復制指定數據生成對應的格式,就需要我們自定義方法了。
代碼如下:
場景是復制一個json對象
function copyTXT () { var data = [ { isSubtraction: 0, columnName: '項目', parentID: '0', reportID: '28', kmdm: null, isSum: 0, intOrder: 1, calculate: 0, id: 25, createTime: 1576547028, createUser: 0, updateTime: 0, updateUser: 0, rowVersion: 'e5cded58baf1442da7304e0463207aac', isDelete: 0 }, { isSubtraction: 0, columnName: '項目', parentID: '0', reportID: '28', kmdm: null, isSum: 0, intOrder: 1, calculate: 0, id: 25, createTime: 1576547028, createUser: 0, updateTime: 0, updateUser: 0, rowVersion: 'e5cded58baf1442da7304e0463207aac', isDelete: 0 } ]; var str = ''; for (var i = 0; i < data.length; i++) { for (let key in data[i]) { str += data[i][key] + '\t'; } str += '\n'; } this.copyTextToClipboard(str); } function copyText (text) { //生成一個textarea對象 var textArea = document.createElement('textarea'); //設置屬性 textArea.style.position = 'fixed'; textArea.style.top = 0; textArea.style.left = 0; textArea.style.width = '2em'; textArea.style.height = '2em'; textArea.style.padding = 0; textArea.style.border = 'none'; textArea.style.outline = 'none'; textArea.style.boxShadow = 'none'; textArea.style.background = 'transparent'; textArea.value = text; //添加到頁面body document.body.appendChild(textArea); textArea.select(); //執行 var msg = document.execCommand('copy') ? '成功' : '失敗'; alert('復制內容' + msg); //移除對象 document.body.removeChild(textArea); }