2010-10-16 228 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