1、簡單的純JS復制粘貼(兼容性差,只能用textarea標簽)
var btn=document.getElementsByClassName("btn")[0]; //復制按鈕
btn.onclick=function(){
var foo = document.getElementById("foo"); //要復制的節點,只能是textarea
foo.select();
document.execCommand("Copy");
}
2、ClipboardJS插件的使用
(一)簡單的使用
<textarea id="foo">123</textarea> //被復制對象
<button class="btn" data-clipboard-target="#foo" data-clipboard-action="copy">復制</button> //復制
new ClipboardJS('.btn');
(二)高級的使用
ClipboardJS.isSupported() //是否兼容
var clipboard = new ClipboardJS('.btn', {
target: function(trigger) {
return document.getElementById("foo") //選擇對象
}
});
var clipboard = new ClipboardJS('.btn', {
text: function(trigger) {
return 123567; //復制內容
}
})
clipboard.on('success', function(e) {
console.info('Action:', e.action); //復制類型
console.info('Text:', e.text); //復制文本
console.info('Trigger:', e.trigger); //復制節點
e.clearSelection(); //取消選擇節點
});
clipboard.on('error', function(e) {
console.error('Action:', e.action);
console.error('Trigger:', e.trigger);
});
