ZeroClipboard
TALK IS CHEAP, SHOW ME THE CODE
// 复制文本内容到剪切板
function copyText(obj) {
if (!obj) {
return false;
}
var text;
if (typeof(obj) == 'object') {
if (obj.nodeType) { // DOM node
obj = $(obj); // to jQuery object
}
try {
text = obj.text();
if (!text) { // Maybe <textarea />
text = obj.val();
}
} catch (err) { // as JSON
text = JSON.stringify(obj);
}
} else {
text = obj;
}
//var $temp = $('<input>'); // Line feed is not supported
var $temp = $('<textarea>');
$('body').append($temp);
$temp.val(text).select();
var res = document.execCommand('copy');
$temp.remove();
return res;
}
调用示例:
<textarea id="taCode" rows="8" style="resize: none"></textarea>
<button type="button" class="btn btn-primary" onclick="copyText($('#taCode'))">复制</button>
<button id="btCopy" type="button" class="btn btn-primary">复制</button>
<script type="text/javascript">
$("#btCopy").click(function() {
//copyText($("#taCode").text());
copyText($("#taCode").val());
});
</script>
封装为 jQuery 插件
笔者已完成封装并开源,欢迎移步 GitHub / jquery-copy 了解。
参考
关于 document.execCommand('copy')
,可以参考在 StackOverflow 上的讨论:
https://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery