3

在提出任何问题之前,我确实对此进行了彻底的研究,并且以前没有在此处发布答案。

我想用 Javascript 将一些纯文本配置文本发送到剪贴板。该文本将包含多个命令,每行一个命令,因此用户可以myconfig.ini使用文本编辑器(最常见的是 Notepad.exe)粘贴到他的 PC 上的配置文件(称为“”)。

我尝试了以下方法:

var cCRLF = String.fromCharCode(10,13);

var cText  = 'This is command line 1'+cCRLF;
cText  += 'This is command line 2'+cCRLF;
cText  += 'This is command line 3'+cCRLF;
cText  += 'This is command line 4';

window.clipboardData.setData('Text', cText);

但是当我执行并粘贴到记事本中时,
我没有得到单独的行,并且
行返回字符(cCRLF)不可见
(出现了那个讨厌的小框字符)。

有人对此有解决方案吗?

4

3 回答 3

3

解决方案是使用反引号(` `)

alert(`string text line 1
string text line 2`);

供参考: https ://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/template_strings

于 2016-02-02T14:40:24.343 回答
0

我建议使用剪贴板以外的其他方法向用户发送数据。此方法仅适用于 IE,可以禁用(较新的 IE 版本先提示):Get clipboard data as array in javascript

CSS 弹出框(用户可以自己复制)可能是一个更好的(和跨平台的)解决方案。这可能会有所帮助: http: //www.pat-burt.com/web-development/how-to-do-a-css-popup-without-opening-a-new-window/

于 2010-10-16T19:06:16.443 回答
0

我想我确实找到了解决方案。这有点奇怪,但是,嘿,它是针对 IE 的。这是我在 stackoverflow 上找到的修改片段。

<body>
    <a href="#" onclick='test("This\nIS\nA\nTEST")'>TEST</a>
    <div id="cb" style="position: absolute; left: -2000px"></div>
</body>
<script>

function test(cText) {
    cText= cText.replace(/\n\r?/g, "<br>");

    // create an editable DIV and append the HTML content you want copied
    var editableDiv = document.getElementById("cb");
    with (editableDiv) {
        contentEditable = true;
    }     
    editableDiv.innerHTML= cText;          

    // 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(document.body);
    r.select();
}

</script>
于 2010-10-16T18:59:14.147 回答