var text = '需要复制的文本';
// ios 下要求更严格, https://stackoverflow.com/questions/34045777/copy-to-clipboard-using-javascript-in-ios
function iosCopyToClipboard(el) {
var oldContentEditable = el.contentEditable,
oldReadOnly = el.readOnly,
range = document.createRange();
el.contentEditable = true;
el.readOnly = false;
range.selectNodeContents(el);
var s = window.getSelection();
s.removeAllRanges();
s.addRange(range);
el.setSelectionRange(0, 999999); // A big number, to cover anything that could be inside the element.
el.contentEditable = oldContentEditable;
el.readOnly = oldReadOnly;
document.execCommand('copy');
}
// pc浏览器
function copyToClipboard() {
var $temp = $("<input>");
$("body").append($temp);
$temp.val(location.href).select();
document.execCommand("copy");
iosCopyToClipboard($temp[0]); // 如果没有这一行,ios下不能复制
$temp.remove();
$(this).html('已复制');
}
$('button').on('click', copyToClipboard);