首页 > 解决方案 > 如何在没有输入文件的情况下创建复制到剪贴板图标?

问题描述

我有这个 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提交的解决方案,但是,如您所见,我只有一段。

我试图在该段落中使用refand 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')
}

标签: javascriptvue.jsvuejs2

解决方案


尝试这个

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('---')
}

推荐阅读