如何将文本复制到剪贴板(多浏览器)?

相关:Trello如何访问用户的剪贴板?


当前回答

从网页读取和修改剪贴板会引发安全和隐私问题。然而,在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”/>

其他回答

我找到了以下解决方案:

按下键处理程序创建一个“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。

复制文本字段内文本的最佳方法。使用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>

这是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除外)都很难做到。就我个人而言,我使用以下简单技巧:

function copyToClipboard(text) {
  window.prompt("Copy to clipboard: Ctrl+C, Enter", text);
}

用户将看到提示框,其中已选择要复制的文本。现在,按下Ctrl+C和Enter键(关闭框)就足够了——瞧!

现在剪贴板复制操作是安全的,因为用户手动执行(但方式非常简单)。当然,它适用于所有浏览器。

<button id=“demo”onclick=“copyToClipboard(document.getElementById('demo').innerHTML)”>这是我要复制的内容</button><脚本>函数复制到剪贴板(文本){window.prpt(“复制到剪贴板:Ctrl+C,Enter”,文本);}</script>

我在从Excel(类似Excel)构建自定义网格编辑以及与Excel的兼容性方面遇到了同样的问题。我必须支持选择多个单元格、复制和粘贴。

解决方案:创建一个文本区域,您将在其中插入数据,供用户复制(当用户选择单元格时为我),设置焦点(例如,当用户按下Ctrl键时)并选择整个文本。

因此,当用户按下Ctrl+C时,他/她会复制他/她选择的单元格。测试后,只需将文本区域调整为一个像素(我没有测试它是否能在显示器上工作:无)。它在所有浏览器上都能很好地工作,并且对用户是透明的。

粘贴-你可以这样做(不同于你的目标)-关注文本区域并使用onpaste捕捉粘贴事件(在我的项目中,我使用单元格中的文本区域进行编辑)。

我不能粘贴一个例子(商业项目),但你明白了。