JS函数复制文本内容到剪切板(兼容所有浏览器)

原理:创建input DOM节点再删除该节点,调用 document.execCommand("Copy"); 方法
应用:当我们需要一个点击事件把 文本内容 复制到剪切板的时候,只需要在自己定义在工具类.js 文件中,引用一下就行,我定义在tool.js中

src/utils/tool.js 中定义

// 复制内容到剪切板, 成功返回true
export function copyString(string){
  if(!string) return false
  let dom = document.createElement('input');
  dom.value = string;
  document.body.appendChild(dom);
  dom.select(); // 选择对象
  document.execCommand("Copy"); // 执行浏览器复制命令
  document.body.removeChild(dom)
  Message.success('内容已经复制到剪切板')
  return true
}

index.vue中使用

<template>
	<div>
		<button @click="copyUrl('www.baidu.com')">复制地址</button>
	</div>
</template>

<script>
import { copyString } from 'src/utils/tool.js'
export default {
	methods: {
		copyUrl(url){
			let flag = copyString(url)
			... 通过返回值 flag 判断接下来的操作
		}
	}
}
</script>
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值