当前位置:网站首页>3种实现文本复制功能的方法
3种实现文本复制功能的方法
2022-07-30 02:21:00 【bug丸】
复制功能的实现方式
一、vue-clipboard
npm install vue-clipboard2 --save
import VueClipboard from 'vue-clipboard2'
Vue.use(VueClipboard)
使用:
<template>
<div class="container">
<input type="text" v-model="content" />
<button
v-clipboard:copy="content"
v-clipboard:success="onCopy"
v-clipboard:error="onError"
>
点击复制
</button>
</div>
</template>
<script>
export default {
data() {
return {
content: "",
};
},
methods: {
onCopy: function(e) {
console.log("复制成功,复制的内容为:", e.text);
},
onError: function(e) {
console.log("复制失败");
},
},
};
</script>
二、navigation.clipboard
navigator.clipboard.writeText() 将指定字符串写入剪切板中,返回一个promise对象
往输入框内输入内容后点击复制,就可以复制了
<input type="text" id="ipt" />
<input type="button" id="btn" value="点击复制" />
<script>
document.querySelector("#btn").addEventListener("click", function() {
navigator.clipboard
.writeText(document.querySelector("#ipt").value)
.then(() => {
alert("复制成功");
})
.catch(() => {
alert("复制失败");
});
});
问题:本地没问题,但是当嵌入到iframe中,复制直接报错了;
cannot read properties of undefined (reading writeText)
只有在用户事先授予网站或应用对剪切板的访问许可之后,才能使用异步剪切板读写方法
解决方法:给iframe添加allow属性
<iframe allow="clipboard-write" src="http://127.0.0.1:5500/src/views/copy.html" />
三、execCommand
如果是input的话可以用,普通的元素不能用,而且select会选中内容,有选中的效果
<input type="text" v-model="content" ref="ipt" />
copyContent() {
this.$refs.ipt.select();
document.execCommand("copy");
}
这种方法不建议使用,已过时
边栏推荐
- centOS安装MySQL详解
- Object.freeze() learning
- 一个塑料瓶的海洋“奇幻漂流”
- HCIP 第十四天
- fluttter学习之ButtonStyle 、MaterialStateProperty
- [Notes] Stuttering word segmentation to draw word cloud map
- win11 自带远程桌面使用(包含非局域网使用以及win11升级为专业版)
- 黑客动态播报 | 一封假offer,盗取6.25亿美元
- Postgresql daily operation and maintenance skills, suitable for beginners
- Sublime does background transparency and column editor
猜你喜欢

Implementation of Portable VR in Unity

Is it difficult for AI to land?Cloud native helps enterprises quickly apply machine learning MLOps

Tibetan Mapping

Zero code tools recommended - HiFlow

The role of interface testing

org.apache.ibatis.binding.BindingException Invalidbound statement (not found)的解决方案和造成原因分析(超详细)

nrm ls 为什么前面不带 *了

Mysql中事务是什么?有什么用?

躲避雪糕刺客?通过爬虫爬取雪糕价格
![[VMWARE--Shared files]](/img/34/1f1609edc82c0a134886f9bf936f7f.png)
[VMWARE--Shared files]
随机推荐
记一次搭建conda虚拟环境
超详细的MySQL三万字总结
[Microservice~Nacos] Configuration Center of Nacos
超详细的MySQL基本操作
[深入研究4G/5G/6G专题-45]: 5G Link Adaption链路自适应-1-总体架构
CSDN外链解决方法 (2022-07-28测试可用)
el-table加合计
Embedded SIG | 分布式软总线
fluttter学习之ButtonStyle 、MaterialStateProperty
English语法_不定代词 -some & any
绘制热度图、频谱图、地形图、colormap
Type-C charging and OTG chip - LDR6028A
博客搭建十:hugo博客添加友链
错误:“filesystem“ 不是 “std“ 的成员
零代码工具推荐---HiFlow
Drawing Problem Log
c语言进阶篇:指针(四)
解决:Error while adding the mapper ‘interface to configuration. Error parsing Mapper XML
STM32L4R9ZIY6PTR STM32L4 high-performance embedded-MCU
LeetCode 2352. Equal Row Column Pairs