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
452 views
in Technique[技术] by (71.8m points)

javascript - 如何通过单击按钮将示例代码复制到剪贴板中?(How do you copy sample code in the clipboard using click of a button [duplicate])

I'm trying to copy code from a code tag using JavaScript.(我正在尝试使用JavaScript从代码标签复制代码。)

It works, but it copies the text in one long line of text.(它可以工作,但是它会将文本复制到一长行文本中。) I want it to copy with the exact format, for an example see this web site: https://leetcode.com/articles/two-sum/#approach-1-brute-force(我希望它以确切的格式复制,例如,请参见以下网站: https : //leetcode.com/articles/two-sum/#approach-1-brute-force) My question, how can I implement the same logic of copy code as in the above website?(我的问题是,如何实现与上述网站相同的copy代码逻辑?) here is my code:(这是我的代码:) copy: function(component,event,text) { // Create an hidden input var hiddenInput = document.createElement("input"); // passed text into the input hiddenInput.setAttribute("value", text); // Append the hiddenInput input to the body document.body.appendChild(hiddenInput); // select the content hiddenInput.select(); // Execute the copy command document.execCommand("copy"); // Remove the input from the body after copy text document.body.removeChild(hiddenInput); }   ask by Nick Kahn translate from so

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

1 Reply

0 votes
by (71.8m points)

The problem is that an input cannot have any newline characters in it, so when you assign a string to its .value , and that string contains newline characters, they just disappear:(问题在于input中不能包含任何换行符,因此当您将字符串分配给.value ,并且该字符串包含换行符时,它们就会消失:)

input.value = 'foo\nbar'; console.log(input.value.includes('\n')); <input id="input"> Use a textarea instead:(改用textarea:) var hiddenInput = document.createElement("textarea");

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

1.4m articles

1.4m replys

5 comments

57.0k users

...