如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
当前回答
clipboard.js是一个小型的非Flash实用程序,允许将文本或HTML数据复制到剪贴板。它非常容易使用,只需包含.js并使用如下内容:
<button id='markup-copy'>Copy Button</button>
<script>
document.getElementById('markup-copy').addEventListener('click', function() {
clipboard.copy({
'text/plain': 'Markup text. Paste me into a rich text editor.',
'text/html': '<i>here</i> is some <b>rich text</b>'
}).then(
function(){console.log('success'); },
function(err){console.log('failure', err);
});
});
</script>
clipboard.js也在GitHub上。
注意:现在已弃用此选项。迁移到此处。
其他回答
我非常成功地使用了这个(没有jQuery或任何其他框架)。
function copyToClp(txt){
var m = document;
txt = m.createTextNode(txt);
var w = window;
var b = m.body;
b.appendChild(txt);
if (b.createTextRange) {
var d = b.createTextRange();
d.moveToElementText(txt);
d.select();
m.execCommand('copy');
}
else {
var d = m.createRange();
var g = w.getSelection;
d.selectNodeContents(txt);
g().removeAllRanges();
g().addRange(d);
m.execCommand('copy');
g().removeAllRanges();
}
txt.remove();
}
警告
制表符转换为空格(至少在Chrome中)。
我找到了以下解决方案:
按下键处理程序创建一个“pre”标记。我们设置要复制到此标记的内容,然后在此标记上进行选择并在处理程序中返回true。这将调用Chrome的标准处理程序并复制选定的文本。
如果需要,您可以为恢复先前选择的函数设置超时。我在MooTools上的实现:
function EnybyClipboard() {
this.saveSelection = false;
this.callback = false;
this.pastedText = false;
this.restoreSelection = function() {
if (this.saveSelection) {
window.getSelection().removeAllRanges();
for (var i = 0; i < this.saveSelection.length; i++) {
window.getSelection().addRange(this.saveSelection[i]);
}
this.saveSelection = false;
}
};
this.copyText = function(text) {
var div = $('special_copy');
if (!div) {
div = new Element('pre', {
'id': 'special_copy',
'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
});
div.injectInside(document.body);
}
div.set('text', text);
if (document.createRange) {
var rng = document.createRange();
rng.selectNodeContents(div);
this.saveSelection = [];
var selection = window.getSelection();
for (var i = 0; i < selection.rangeCount; i++) {
this.saveSelection[i] = selection.getRangeAt(i);
}
window.getSelection().removeAllRanges();
window.getSelection().addRange(rng);
setTimeout(this.restoreSelection.bind(this), 100);
} else return alert('Copy did not work. :(');
};
this.getPastedText = function() {
if (!this.pastedText) alert('Nothing to paste. :(');
return this.pastedText;
};
this.pasteText = function(callback) {
var div = $('special_paste');
if (!div) {
div = new Element('textarea', {
'id': 'special_paste',
'style': 'opacity: 0;position: absolute;top: -10000px;right: 0;'
});
div.injectInside(document.body);
div.addEvent('keyup', function() {
if (this.callback) {
this.pastedText = $('special_paste').get('value');
this.callback.call(null, this.pastedText);
this.callback = false;
this.pastedText = false;
setTimeout(this.restoreSelection.bind(this), 100);
}
}.bind(this));
}
div.set('value', '');
if (document.createRange) {
var rng = document.createRange();
rng.selectNodeContents(div);
this.saveSelection = [];
var selection = window.getSelection();
for (var i = 0; i < selection.rangeCount; i++) {
this.saveSelection[i] = selection.getRangeAt(i);
}
window.getSelection().removeAllRanges();
window.getSelection().addRange(rng);
div.focus();
this.callback = callback;
} else return alert('Failed to paste. :(');
};
}
用法:
enyby_clip = new EnybyClipboard(); // Init
enyby_clip.copyText('some_text'); // Place this in the Ctrl+C handler and return true;
enyby_clip.pasteText(function callback(pasted_text) {
alert(pasted_text);
}); // Place this in Ctrl+V handler and return true;
在粘贴时,它会创建一个文本区域,并以相同的方式工作。
PS:也许这个解决方案可以用于创建没有Flash的完整跨浏览器解决方案。它适用于Firefox和Chrome。
2018年,你可以这样做:
async copySomething(text?) {
try {
const toCopy = text || location.href;
await navigator.clipboard.writeText(toCopy);
console.log('Text or Page URL copied');
}
catch (err) {
console.error('Failed to copy: ', err);
}
}
它在我的Angular 6+代码中使用如下:
<button mat-menu-item (click)="copySomething()">
<span>Copy link</span>
</button>
如果我传入一个字符串,它就会复制它。如果没有,它会复制页面的URL。
也可以在剪贴板上做更多的体操。在此处查看更多信息:
取消阻止剪贴板访问
clipboard.js是一个小型的非Flash实用程序,允许将文本或HTML数据复制到剪贴板。它非常容易使用,只需包含.js并使用如下内容:
<button id='markup-copy'>Copy Button</button>
<script>
document.getElementById('markup-copy').addEventListener('click', function() {
clipboard.copy({
'text/plain': 'Markup text. Paste me into a rich text editor.',
'text/html': '<i>here</i> is some <b>rich text</b>'
}).then(
function(){console.log('success'); },
function(err){console.log('failure', err);
});
});
</script>
clipboard.js也在GitHub上。
注意:现在已弃用此选项。迁移到此处。
这是Chase Seibert答案的扩展,其优点是它适用于IMAGE和TABLE元素,而不仅仅是Internet Explorer 9上的DIV。
if (document.createRange) {
// Internet Explorer 9 and modern browsers
var r = document.createRange();
r.setStartBefore(to_copy);
r.setEndAfter(to_copy);
r.selectNode(to_copy);
var sel = window.getSelection();
sel.addRange(r);
document.execCommand('Copy'); // Does nothing on Firefox
} else {
// Internet Explorer 8 and earlier. This stuff won't work
// on Internet Explorer 9.
// (unless forced into a backward compatibility mode,
// or selecting plain divs, not img or table).
var r = document.body.createTextRange();
r.moveToElementText(to_copy);
r.select()
r.execCommand('Copy');
}