Javascript 如何将代码复制到<;代码>;标记到剪贴板?
我试过这个代码,但不起作用。如何将Javascript 如何将代码复制到<;代码>;标记到剪贴板?,javascript,html,vue.js,Javascript,Html,Vue.js,我试过这个代码,但不起作用。如何将标记中的代码复制到剪贴板 <pre id="myCode"> <code> console.log("hello world!") </code> </pre> JavaScript function copyScript(){ document.getElementById('myCode').select(); document.exe
标记中的代码复制到剪贴板
<pre id="myCode">
<code>
console.log("hello world!")
</code>
</pre>
JavaScript
function copyScript(){
document.getElementById('myCode').select();
document.execCommand('copy');
}
该功能只能用于输入元素,如
或
如果要将其与
标记一起使用,一种实现方法是将标记的内容复制到新的
对象中,然后从该对象进行复制:
function copyScript() {
// get the text to copy
var codeText = document.getElementById('myCode').textContent;
// create a textarea with the text we want to copy and add it to the page
var textArea = document.createElement('textarea');
textArea.textContent = codeText;
document.body.append(textArea);
// focus on the new textarea and copy the contents!
textArea.focus();
textArea.select();
document.execCommand('copy');
}
我会为现代浏览器做这件事
function copyToClipboard {
let codeText = document.getElementById('myCode').textContent;
// copying
navigator.clipboard.writeText(codeText)
}
这回答了你的问题吗?如何将此代码用于vue.js?@FurkanKarakuzu我认为您不需要依赖框架,它内置于JavaScript中。