js复制文本到剪切板
复制粘贴这个功能我们应该都已经非常熟悉了,但是在特殊情况的时候,需要复制指定数据生成对应的格式,就需要我们自定义方法了。
代码如下:
场景是复制一个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); }