兼容IE和H5的“复制大法“--document.execCommand

兼容IE和H5的JavaScript复制功能的代码:document.execCommand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
//复制到剪贴板

function copyTextToClipboard(text, callback) {

var textArea = document.createElement("textarea");
textArea.style.position = 'fixed';
textArea.style.top = 0;
zextArea.style.left = 0;
textArea.style.width = '.1em';
textArea.style.height = '.1em';
textArea.style.padding = 0;
textArea.style.border = 'none';
textArea.style.outline = 'none';
textArea.style.boxShadow = 'none';
textArea.style.background = 'transparent';
textArea.value = text;
document.body.appendChild(textArea);
textArea.select();

try {

//var msg = document.execCommand('copy') ? '成功' : '失败';
//console.log('复制内容 ' + msg);
if (document.execCommand('copy')) {
return callback();
}

return console.log('复制内容 ' + msg);
} catch (err) {
console.log('不能使用这种方法复制内容');
}
document.body.removeChild(textArea);
}

资料原文链接 http://www.jianshu.com/p/37322bb86a48

0%