如何在复制和粘贴列表项时添加换行符

How can I add line breaks when copying & pasting list items?

本文关键字:列表 添加 换行符 复制      更新时间:2023-09-26

当有人从我的网站复制文本时,我想在每个列表项之间放置一个额外的换行符,因为项目符号不会复制。我该怎么做?

这个问题的答案只是告诉你如何在复制文本的开头和/或结尾添加代码,我想在列表项之间添加代码!

代码非常简单:

<div>
  <li>This is the first paragraph.</li>
  <li>This is the second.</li>
  <li>This is the third.</li>
</div>
<textarea>Copy &amp; paste here with breaks in between each list item.</textarea>

https://jsfiddle.net/cleo_not_chloe/pvn3ahtr/

谢谢!

  • 使用.on("copy", callback)检测用户使用鼠标复制的文本或键盘 ( Ctrl + c (。
  • 使用window.getSelection()获取所选文本并将其自定义为您喜欢删除,添加或替换文本。在这里我用了 .replace(/'n/g,"'n'n")将每个中断线加倍。
  • 使用.on("paste", callback)事件设置#textarea值自定义复制的文本。
  • <textarea>应由纯文本填充,因此请使用.val()而不是.innerHTML.html()

//create global variable to store copied text.
var s;
//listen to copy for your element
$("#text").on("copy", function() {
  //get selected text while coping  
  s = window.getSelection().toString();
  //customize breaklines to be double
  s = s.replace(/'n/g, "'n'n");
  //add break line to the end and more text
  s += "'n" + "- More text says you are welcome";
  //HTML will displays as plain text in textarea
  s += "'n" + "- <p>Hello world</p>";
});
// listen to paste
$("#textarea").on("paste", function() {
  //set value with your customized copied text
  $("#textarea").val(s);
  return false;
});
li {
  list-style-type: none;
}
#savebox {
  float: right;
}
#textarea {
  height: 200px;
  width: 200px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="text" contenteditable="true">
  <ul>
    <li>This is the first paragraph.</li>
    <li>This is the second.</li>
    <li>This is the third.</li>
  </ul>
</div>
<div id="savebox">
  <textarea id="textarea">Copy &amp; paste here with breaks in between each list item.</textarea>
</div>