ZeroClipboard
TALK IS CHEAP, SHOW ME THE CODE
// 復(fù)制文本內(nèi)容到剪切板
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;
}
調(diào)用示例:
<textarea id="taCode" rows="8" style="resize: none"></textarea>
<button type="button" class="btn btn-primary" onclick="copyText($('#taCode'))">復(fù)制</button>
<button id="btCopy" type="button" class="btn btn-primary">復(fù)制</button>
<script type="text/javascript">
$("#btCopy").click(function() {
//copyText($("#taCode").text());
copyText($("#taCode").val());
});
</script>
封裝為 jQuery 插件
筆者已完成封裝并開源认烁,歡迎移步 GitHub / jquery-copy 了解荚虚。
參考
關(guān)于 document.execCommand('copy')
,可以參考在 StackOverflow 上的討論:
https://stackoverflow.com/questions/22581345/click-button-copy-to-clipboard-using-jquery