如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
当前回答
我喜欢这个:
<input onclick="this.select();" type='text' value='copy me' />
如果用户不知道如何在操作系统中复制文本,那么他们很可能也不知道如何粘贴。因此,只需自动选择它,剩下的留给用户。
其他回答
我喜欢这个:
<input onclick="this.select();" type='text' value='copy me' />
如果用户不知道如何在操作系统中复制文本,那么他们很可能也不知道如何粘贴。因此,只需自动选择它,剩下的留给用户。
我非常成功地使用了这个(没有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中)。
这是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');
}
从网页读取和修改剪贴板会引发安全和隐私问题。然而,在Internet Explorer中,可以这样做。我找到了以下示例片段:
<script type=“text/javascript”>函数select_all(obj){var text_val=评估(对象);text_val.focus();text_val.select();r=text_val.createTextRange();if(!r.execCommand)return;//特征检测r.execCommand('copy');}</script><输入值=“http://www.sajithmr.com"onclick=“select_all(this)”name=“url”type=“text”/>
其他方法将纯文本复制到剪贴板。要复制HTML(即,可以将结果粘贴到所见即所得编辑器中),只能在Internet Explorer中执行以下操作。这与其他方法有根本不同,因为浏览器实际上可以直观地选择内容。
// Create an editable DIV and append the HTML content you want copied
var editableDiv = document.createElement("div");
with (editableDiv) {
contentEditable = true;
}
editableDiv.appendChild(someContentElement);
// Select the editable content and copy it to the clipboard
var r = document.body.createTextRange();
r.moveToElementText(editableDiv);
r.select();
r.execCommand("Copy");
// Deselect, so the browser doesn't leave the element visibly selected
r.moveToElementText(someHiddenDiv);
r.select();