如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
如何将文本复制到剪贴板(多浏览器)?
相关:Trello如何访问用户的剪贴板?
当前回答
我找到了以下解决方案:
按下键处理程序创建一个“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。
其他回答
由于Chrome 42+和Firefox 41+现在支持document.execCommand('copy')命令,我结合Tim Down的旧答案和Google Developer的答案,创建了两个跨浏览器复制到剪贴板的功能:
函数selectElementContents(el){//复制textarea、pre、div等。if(document.body.createTextRange){//Internet Explorervar textRange=document.body.createTextRange();text范围.移动到元素文本(el);text范围.选择();textRange.execCommand(“复制”);}否则如果(window.getSelection&&document.createRange){//非Internet Explorervar range=document.createRange();range.selectNodeContents(el);var sel=window.getSelection();sel.removeAllRanges();sel.addRange(范围);尝试{var success=document.execCommand('copy');var msg=成功?'success':'不成功';console.log('复制命令为'+msg);}捕获(错误){console.log(“糟糕,无法复制”);}}}//结束函数selectElementContents(el)函数make_copy_button(el){var copy_btn=document.createElement('input');copy_btn.type=“按钮”;el.parentNode.insertBefore(copy_btn,el.nexSibling);copy_btn.onclick=函数(){selectElementContents(el);};if(document.queryCommandSupported(“copy”)||parseInt(navigator.userAgent.match(/Chrom(e|ium)\/([0-9]+)\./)[2]) >= 42) {//复制适用于Internet Explorer 4+、Chrome 42+、Firefox 41+、Opera 29+copy_btn.value=“复制到剪贴板”;}其他{//仅适用于Safari和旧版Chrome、Firefox和Operacopy_btn.value=“全选(然后按Ctrl+C复制)”;}}/*注意:document.queryCommandSupported(“copy”)在支持复制的浏览器上应返回“true”,但Chrome版本42到47中存在一个错误,使其返回“false”。所以在那些版本的Chrome功能检测不起作用!看见https://code.google.com/p/chromium/issues/detail?id=476508*/make_copy_button(document.getElementById(“标记”));<pre-id=“markup”>可以通过跨浏览器支持复制或选择的文本。</pre>
从网页读取和修改剪贴板会引发安全和隐私问题。然而,在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”/>
我在从Excel(类似Excel)构建自定义网格编辑以及与Excel的兼容性方面遇到了同样的问题。我必须支持选择多个单元格、复制和粘贴。
解决方案:创建一个文本区域,您将在其中插入数据,供用户复制(当用户选择单元格时为我),设置焦点(例如,当用户按下Ctrl键时)并选择整个文本。
因此,当用户按下Ctrl+C时,他/她会复制他/她选择的单元格。测试后,只需将文本区域调整为一个像素(我没有测试它是否能在显示器上工作:无)。它在所有浏览器上都能很好地工作,并且对用户是透明的。
粘贴-你可以这样做(不同于你的目标)-关注文本区域并使用onpaste捕捉粘贴事件(在我的项目中,我使用单元格中的文本区域进行编辑)。
我不能粘贴一个例子(商业项目),但你明白了。
ZeroClipboard是我找到的最好的跨浏览器解决方案:
<div id="copy" data-clipboard-text="Copy Me!">Click to copy</div>
<script src="ZeroClipboard.js"></script>
<script>
var clip = new ZeroClipboard( document.getElementById('copy') );
</script>
如果您需要iOS的非Flash支持,只需添加一个回退:
clip.on( 'noflash', function ( client, args ) {
$("#copy").click(function(){
var txt = $(this).attr('data-clipboard-text');
prompt ("Copy link, then click OK.", txt);
});
});
http://zeroclipboard.org/
https://github.com/zeroclipboard/ZeroClipboard
复制文本字段内文本的最佳方法。使用navigator.clipboard.writeText。
<input type="text" value="Hello World" id="myId">
<button onclick="myFunction()" >Copy text</button>
<script>
function myFunction() {
var copyText = document.getElementById("myId");
copyText.select();
copyText.setSelectionRange(0, 99999);
navigator.clipboard.writeText(copyText.value);
}
</script>