javascript - 如何在没有输入文件的情况下创建复制到剪贴板图标?
问题描述
我有这个 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
and 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('---')
}
推荐阅读
- nuxt.js - Nuxt _vm._ssrNode 在运行 yarn dev 时不是函数
- material-ui - 抽屉打开时,材质 UI 更改背景的不透明度
- uipageviewcontroller - 正确解决新的快速点击动画模式/避免Apple新UIPageControl的半页错误
- javascript - Chrome 扩展,显示请求表单数据
- python - 如何通过python脚本检查访问表单是否打开
- sql - 有没有办法让 T-SQL 中的普通整数列唯一?
- android - 有没有办法找出给定镜头的 LENS_INTRINSIC_CALIBRATION 数据?
- svg - 如何摆脱 SVG 中第一个字形之前的空间
元素? - arraylist - 在 swift 5 中从 PHAsset 数组中获取数据
- firebase - Firebase 消息传递 - 当应用程序关闭或在 Flutter 中休眠时不会发送通知