当前位置:网站首页>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");
}
这种方法不建议使用,已过时
边栏推荐
- 基于低能耗自适应聚类层次结构(LEACH)(Matlab代码实现)
- Postgresql daily operation and maintenance skills, suitable for beginners
- Implementation of Portable VR in Unity
- consul operation
- Tcp ip
- LeetCode Question of the Day (874. Walking Robot Simulation)
- Push the image to the Alibaba Cloud private warehouse
- 自动配置和 thymeleaf模板引擎
- LeetCode每日一题(874. Walking Robot Simulation)
- Kotlin接口
猜你喜欢
随机推荐
一文读懂Elephant Swap,为何为ePLATO带来如此高的溢价?
Understanding the prototype chain in js, what problem does the prototype chain solve?
将镜像推送到阿里云私有仓库
基于蒙特卡诺的风场景模型出力(Matlab代码实现)
Google浏览器打开axure产品原型的解决方案
【C语言刷LeetCode】592. 分数加减运算(M)
JS develops 3D modeling software
躲避雪糕刺客?通过爬虫爬取雪糕价格
LeetCode 2342. Digital and equal number of one of the biggest and
Tibetan Mapping
STM32L4R9ZIY6PTR STM32L4高性能嵌入式—MCU
多线程---初阶
信息系统项目管理师核心考点(五十四)配置项分类、状态与版本
力扣刷题训练(二)
基于燃压缩空气储能系统的零碳微能源互联网优化调度(Matlab代码实现)
测试/开发程序员面试该如何谈薪资待遇呢?突破这个坎......
JNPF3.4.2系统升级公告
基于低能耗自适应聚类层次结构(LEACH)(Matlab代码实现)
二叉搜索树
【机器学习】通俗易懂决策树(原理篇)









