Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
653 views
in Technique[技术] by (71.8m points)

javascript - Copy Button Preserving Line Breaks

I have some very basic Javascript that copies text upon the push of a button. My problem is that it doesnt preserve line breaks:

<script>
function copyToClipboard(element) {
  var $temp = $("<input>");
  $("body").append($temp);
  $temp.val($(element).text()).select();
  document.execCommand("copy");
  $temp.remove();
}
</script>

I'd really like something to be able to be added to the above script to avoid making huge changes on the site already.

I've seen things on other posts such as:

post.innerHTML = post.innerHTML.replace(/
/g, '<br>
');

which in theory would work (i think) but I suck at Javascript.

Any suggestions?

Thanks

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

First off, the <input> element doesn't preserve line breaks. You can use the <textarea> element instead. Since your HTML may contain <br> elements instead of line break characters, I would also suggest using jQuery to prepend before each <br>.

function copyToClipboard(element) {
  var text = $(element).clone().find('br').prepend('
').end().text()
  element = $('<textarea>').appendTo('body').val(text).select()
  document.execCommand('copy')
  element.remove()
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p contenteditable="true">Type to edit <br> this text</p>
<button onclick="copyToClipboard('p')">Copy to Clipboard</button>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...