随着Flash在许多环境中逐渐退出(iPhone、Android、IE10等),是否有任何新的解决方案在任何浏览器中即使没有安装Flash也能够安全地复制信息到剪贴板?
到目前为止,我一直在使用ZeroClipboard,但我担心更多的观众没有安装Flash,这个功能将会失效,我希望尽可能不依赖Flash。
到目前为止,我一直在使用ZeroClipboard,但我担心更多的观众没有安装Flash,这个功能将会失效,我希望尽可能不依赖Flash。
function copyToClipboard (text) {
window.prompt ("Copy to clipboard: Ctrl+C, Enter", text);
}
这段文字是从Jarek Milewski那里得到的,当时有人在这里提出了问题。
*我找到了一个在IE中可行的解决方案,但在大多数现代浏览器中不起作用,请查看此处。
更新:
根据https://developer.mozilla.org/en-US/docs/Web/API/Document/execCommand,Firefox 41+、Chrome 42+和IE 9+支持使用execCommand复制命令。对于Firefox和Chrome,只有在用户操作(例如单击)触发时才会起作用;对于IE,则会弹出警告对话框,要求用户允许将内容复制到剪贴板。
我知道这个答案有点晚了,但现在有一个新的现代化替代方案可以代替基于Flash的ZeroClipboard。 Clipboard.js 是一个2kB纯JavaScript的替代品,没有任何依赖。
我创建了一个名为clip-j的纯JavaScript解决方案。 这里 是它的代码。基本上它利用了document.execCommand('copy');
和其他几个命令,使你看不到任何东西。以下是代码:
function clip(text) {
var copyElement = document.createElement('input');
copyElement.setAttribute('type', 'text');
copyElement.setAttribute('value', text);
copyElement = document.body.appendChild(copyElement);
copyElement.select();
document.execCommand('copy');
copyElement.remove();
}
contentEditable
属性设置为true
的div
(而不是input
),则还可以将其作为text/html
复制到剪贴板中,从而保留格式。请参见此答案:https://dev59.com/SWEh5IYBdhLWcg3wTB1c#30905277 - Krisztián Balla这个问题有很棒的答案在这里, 而我选择使用这段代码:
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
$temp.val($(element).text()).select()
这行代码将会抛出一个错误:
您可以像jQuery文档中的.select()所述,使用该小部件只能在选择元素上工作
.trigger('select')
代替,像这样:$temp.val($(element).val()).trigger('select');
function copyToClipboard(id) {
var blnCopied;
document.getElementById(id).select();
blnCopied = document.execCommand("copy", false, null);
if (blnCopied)
alert('Link copied to clipboard');
else
window.prompt ("Copy to clipboard: Ctrl+C, Enter", jQuery("#"+id).val());
}
使用标准的“a”锚点标签,并添加onclick="copyToClipboard('some_id')"属性