2010-10-16 221 views
2

在提出任何问题之前,我已经彻底研究过了,并且答案之前未在此处发布过。通过Javascript将换行符粘贴到剪贴板中

我想用Javascript将一些纯文本配置文本发送到剪贴板。文本将由多个命令组成,每行一个命令,以便用户可以使用文本编辑器(最常见的是Notepad.exe)将其过滤到PC上的配置文件中(称为“myconfig.ini”)。

我试过如下:

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)是不可见的
(即讨厌的小框字符出现)。

有人有这方面的解决方案吗?

回答

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> 
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/

+0

OK,感谢所有。我想我会去CSS弹出路线。我同意,更清洁的解决方案。 – user478094 2010-10-16 21:31:02

+0

user478094,如何选择答案,以便您的问题被标记为已解决? Thx – kanaka 2010-10-17 20:27:53