vue / JavaScript 中一键复制

方法一:document.execCommand()

问题:已弃用 新版浏览器中无法使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>复制文本到剪贴板</title>
    <style>
        #text-to-copy {
            margin-bottom: 10px;
            padding: 5px;
            border: 1px solid #ccc;
        }
    </style>
</head>
<body>
    <input type="text" id="text-to-copy" value="这里是要复制的文本" readonly>
    <button onclick="copyText()">复制文本</button>

    <script>
        function copyText() {
            // 获取要复制的文本框元素
            const textElement = document.getElementById('text-to-copy');
            
            // 选择文本框中的文本
            textElement.select();
            textElement.setSelectionRange(0, 99999); // 对于手机设备,必须手动设置范围

            // 执行复制操作
            try {
                const successful = document.execCommand('copy');
                if (successful) {
                    alert('文本已复制到剪贴板!');
                } else {
                    alert('复制失败,请手动复制!');
                }
            } catch (err) {
                alert('复制失败!');
            }
        }
    </script>
</body>
</html>

方法二:Clipboard

问题: 只能在localhost 与 https 中使用

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>复制文本到剪贴板</title>
</head>
<body>
    <input type="text" id="text-to-copy" value="这里是要复制的文本" readonly>
    <button onclick="copyText()">复制文本</button>

    <script>
        async function copyText() {
            const textElement = document.getElementById('text-to-copy');
            try {
                await navigator.clipboard.writeText(textElement.value);
                alert('文本已复制到剪贴板!');
            } catch (err) {
                alert('复制失败!');
            }
        }
    </script>
</body>
</html>

方法三:Clipboard.js(推荐使用)

官方文档地址
在 vue 中实现

	npm install clipboard --save
	
	import ClipboardJS from 'clipboard'
	
	<el-button
	 id="copyBtn"
	 type="text"
	 :data-clipboard-text="text"
	>
	  点击复制
	</el-button>

	mounted() {
	  this.copyInit()
	},
	
	beforeDestroy() {
	    // 在组件销毁时销毁 ClipboardJS 实例,避免重复初始化
	    if (this.clipboard) {
	      this.clipboard.destroy()
	    }
  	},
	methods:{
	  copyInit() {
	    const clipboard = new ClipboardJS('#copyBtn')
	    clipboard.on('success', (e) => {
	      this.$message.success('复制成功')
	    })
	  },
	}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值