javascript 使用断线复制到剪贴板
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/46041831/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Copy to clipboard with break line
提问by JohanSellberg
I want to copy a text to clipboard but in a new line.
我想将文本复制到剪贴板,但要另起一行。
Problem:
问题:
If you click the button in the snippet and paste in the notepad this is what you gonna get:
如果您单击代码段中的按钮并粘贴到记事本中,这就是您将得到的:
Name: testSurname: testEmail: [email protected]: testCity: testCountry: nullAd Category: testPlan: nullWebsite: Company name: testΜ?νυμα: test
姓名:testSurname:testEmail:[email protected]:testCity:testCountry:null广告类别:testPlan:null网站:公司名称:testM?νυμα:test
What I want:
我想要的是:
I want, if possible, to copy text in a newline. The same as it is when you copy it:
如果可能,我想在换行符中复制文本。与复制时相同:
Name: test
Surname: test
Email: [email protected]
...
姓名:test
姓:test
邮箱:[email protected]
...
function copyToClipboard(element) {
var $temp = $("<input>");
$("body").append($temp);
$temp.val($(element).text()).select();
document.execCommand("copy");
$temp.remove();
}
$( "#FailCopy" ).click(function() {
alert("Well done! div #error-details has been copy to your clipboard, now paste it in the notepad or email!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--text that i want to copy-->
<h2>Div #error-details: the text I want to copy to clipboard:</h2>
<er id="error-details">Name: test<br>Surname: test<br>Email: [email protected]<br>Address: test<br>City: test<br>Country: null<br>Ad Category: test<br>Plan: null<br>Website: <br>Company name: test<br>Μ?νυμα: test</er>
<br><br>
<button id="FailCopy" type="button"
onclick="copyToClipboard('er#error-details')">Copy div to clipboard</button>
I have also tried to replace <br>with \nand \r\nby adding the following css rule to my div: white-space:pre-wrap;without any signs of success.
我也曾尝试更换<br>与\n和\r\n通过添加下面的CSS规则我的div:white-space:pre-wrap;没有成功的任何迹象。
回答by JohanSellberg
You have a few problems with the code.
您的代码有一些问题。
First problem in your code is the $(element).text()jquery text() strips your code from html including the <br>tags. So there is no newlines in the clipboard text since all html newlines are stripped away.. so nothing to replace.
您的代码中的第一个问题是$(element).text()jquery text() 从 html 中删除您的代码,包括<br>标签。所以剪贴板文本中没有换行符,因为所有的 html 换行符都被删除了......所以没有什么可以替换的。
If you want to keep <br>as newlines you need to use .html()and parse your text more manually.
如果您想保留<br>换行符,则需要.html()更手动地使用和解析文本。
Second problem is that you use <input>tag. <input>tag is only single lines so u cant have any newline in there. you need to use <textarea>for the conversion.
第二个问题是你使用<input>标签。<input>标签只是单行,所以你不能在那里有任何换行符。您需要<textarea>用于转换。
The last problem is as above that you also should use \r\nfor windows users.
最后一个问题如上所述,您也应该\r\n用于 Windows 用户。
I updated your snippet with a working version.
我用一个工作版本更新了你的代码片段。
function copyToClipboard(element) {
var $temp = $("<textarea>");
var brRegex = /<br\s*[\/]?>/gi;
$("body").append($temp);
$temp.val($(element).html().replace(brRegex, "\r\n")).select();
document.execCommand("copy");
$temp.remove();
}
$( "#FailCopy" ).click(function() {
alert("Well done! div #error-details has been copy to your clipboard, now paste it in the notepad or email!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--text that i want to copy-->
<h2>Div #error-details: the text I want to copy to clipboard:</h2>
<er id="error-details">Name: test<br>Surname: test<br>Email: [email protected]<br>Address: test<br>City: test<br>Country: null<br>Ad Category: test<br>Plan: null<br>Website: <br>Company name: test<br>Μ?νυμα: test</er>
<br><br>
<button id="FailCopy" type="button"
onclick="copyToClipboard('er#error-details')">Copy div to clipboard</button>
回答by keshavDulal
Non-jQuery Solution to simply copy a string with line breaks to clipboard
非 jQuery 解决方案,只需将带换行符的字符串复制到剪贴板
Please refer to code comments for clarity.
为清楚起见,请参阅代码注释。
function copyStringWithNewLineToClipBoard(stringWithNewLines){
// Step 1: create a textarea element.
// It is capable of holding linebreaks (newlines) unlike "input" element
const myFluffyTextarea = document.createElement('textarea');
// Step 2: Store your string in innerHTML of myFluffyTextarea element
myFluffyTextarea.innerHTML = stringWithNewLines;
// Step3: find an id element within the body to append your myFluffyTextarea there temporarily
const parentElement = document.getElementById('any-id-within-any-body-element');
parentElement.appendChild(textarea);
// Step 4: Simulate selection of your text from myFluffyTextarea programmatically
myFluffyTextarea.select();
// Step 5: simulate copy command (ctrl+c)
// now your string with newlines should be copied to your clipboard
document.execCommand('copy');
// Step 6: Now you can get rid of your fluffy textarea element
parentElement.removeChild(myFluffyTextarea);
}
回答by TheChetan
Two things are wrong:
有两点是错误的:
(1) According to the jquery documentation for text:
(1)根据文本的jquery文档:
The result of the .text() method is a string containing the combined text of all matched elements. (Due to variations in the HTML parsers in different browsers, the text returned may vary in newlines and other white space.)
.text() 方法的结果是一个包含所有匹配元素的组合文本的字符串。(由于不同浏览器中 HTML 解析器的差异,返回的文本可能在换行符和其他空白处有所不同。)
And their example,
还有他们的榜样,
<div class="demo-container">
<div class="demo-box">Demonstration Box</div>
<ul>
<li>list item 1</li>
<li>list <strong>item</strong> 2</li>
</ul>
</div>
The code $( "div.demo-container" ).text()will produce:
代码$( "div.demo-container" ).text()将产生:
Demonstration Box list item 1 list item 2
Demonstration Box list item 1 list item 2
So just use the html()method instead to fetch the innerHTML.
所以只需使用该html()方法来获取innerHTML.
(2) The <input>tag removes newlines. Use textareainstead. See: this answerfor more info.
(2)<input>标签删除换行符。使用textarea来代替。请参阅:此答案以获取更多信息。
Hopefully this spinet will work.
希望这个spinet会起作用。
function copyToClipboard(element) {
var $temp = $("<textarea>");
$("body").append($temp);
var html = $(element).html();
html = html.replace(/<br>/g, "\n"); // or \r\n
console.log(html);
$temp.val(html).select();
document.execCommand("copy");
$temp.remove();
}
$( "#FailCopy" ).click(function() {
alert("Well done! div #error-details has been copy to your clipboard, now paste it in the notepad or email!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<!--text that i want to copy-->
<h2>Div #error-details: the text I want to copy to clipboard:</h2>
<er id="error-details">Name: test<br>Surname: test<br>Email: [email protected]<br>Address: test<br>City: test<br>Country: null<br>Ad Category: test<br>Plan: null<br>Website: <br>Company name: test<br>Μ?νυμα: test</er>
<br><br>
<button id="FailCopy" type="button"
onclick="copyToClipboard('er#error-details')">Copy div to clipboard</button>
回答by Aenadon
Your code is probably working well, but Notepad can't handle Unix' \n newlines, it only can handle \r\n and this is why you don't see them.
您的代码可能运行良好,但记事本无法处理 Unix 的 \n 换行符,它只能处理 \r\n 而这就是您看不到它们的原因。
Please download a more advanced editor (like Notepad++, https://notepad-plus-plus.org) and try pasting it there. And not only that, but it has a lot of other very cool features like syntax highlighting, macros and plugins so it's worth using it for more purposes than that.
请下载更高级的编辑器(如 Notepad++、https://notepad-plus-plus.org)并尝试将其粘贴到那里。不仅如此,它还具有许多其他非常酷的功能,例如语法突出显示、宏和插件,因此值得将其用于更多用途。
If you want to make the newlines work in MS apps, you need to replace the newlines just before you copy by using this line:
如果您想让换行符在 MS 应用程序中工作,您需要在使用以下行复制之前替换换行符:
$temp = $temp.replace(/\n/g, "\r\n");
For printing in HTML you would need to replace \n with
, like this:
要在 HTML 中打印,您需要将 \n 替换为
,如下所示:
$temp = $temp.replace(/\n/g, "<br>");

