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

时间:2016-11-10 00:38:58

标签: javascript jquery html css

当有人从我的网站复制文本时,我希望在每个列表项之间添加额外的换行符,因为项目符号点不会复制。我怎么能这样做?

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

代码非常简单:

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

谢谢!

1 个答案:

答案 0 :(得分:0)

  • 使用.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>