如何在没有输入字段的情况下创建复制到剪贴板图标?
How to create copy to clipboard icon without input filed?
我有这个 Vue.js 代码:
<div class="border">
<h4>{{ name }}</h4>
<div class="code">
<p>{{ code }}</p>
<img src="~/assets/img/copy.svg" alt="" @click="copy"/>
</div>
</div>
复制按钮有copy
功能。我想要的是复制剪贴板中的 code
字段。我在互联网上寻找解决方案,但只有 input
归档的解决方案,但是,如您所见,我只有段落。
我试图在该段中使用 ref
和 id
,但它不起作用。 ref
:
<p ref='code'>{{ code }}</p>
copy() {
this.$refs.code.focus()
document.execCommand('copy')
}
与id
:
<p id='code'>{{ code }}</p>
copy(id) {
const input = document.querySelector(`#${id}`)
input.setAttribute('type', 'text')
input.select()
document.execCommand('copy')
input.setAttribute('type', 'hidden')
}
试试这个
Html
<p id="text_element">Copy this !</p>
<button onclick="copyToClipboard('text_element')">
Copy to clipboard
</button>
Javascript
function copyToClipboard(elementId) {
var aux = document.createElement("input");
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
document.body.removeChild(aux);}
function log() {
console.log('---')
}
我有这个 Vue.js 代码:
<div class="border">
<h4>{{ name }}</h4>
<div class="code">
<p>{{ code }}</p>
<img src="~/assets/img/copy.svg" alt="" @click="copy"/>
</div>
</div>
复制按钮有copy
功能。我想要的是复制剪贴板中的 code
字段。我在互联网上寻找解决方案,但只有 input
归档的解决方案,但是,如您所见,我只有段落。
我试图在该段中使用 ref
和 id
,但它不起作用。 ref
:
<p ref='code'>{{ code }}</p>
copy() {
this.$refs.code.focus()
document.execCommand('copy')
}
与id
:
<p id='code'>{{ code }}</p>
copy(id) {
const input = document.querySelector(`#${id}`)
input.setAttribute('type', 'text')
input.select()
document.execCommand('copy')
input.setAttribute('type', 'hidden')
}
试试这个
Html
<p id="text_element">Copy this !</p>
<button onclick="copyToClipboard('text_element')">
Copy to clipboard
</button>
Javascript
function copyToClipboard(elementId) {
var aux = document.createElement("input");
aux.setAttribute("value", document.getElementById(elementId).innerHTML);
document.body.appendChild(aux);
aux.select();
document.execCommand("copy");
document.body.removeChild(aux);}
function log() {
console.log('---')
}