js系列-复制内容到粘贴板剪切板

本文介绍了如何利用JavaScript的document.execCommand()方法来实现在网页中复制文本的功能,包括对输入框内容的复制以及对于非输入框元素的复制策略。通过创建隐藏的textarea元素,将目标内容填入并选中,再调用execCommand('copy')来完成复制操作。这种方法适用于处理可编辑区域以外的内容复制需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

document.execCommand()方法

先看看这个方法在 MDN 上是怎么定义的:

which allows one to run commands to manipulate the contents of 
the editable region.

意思就是可以允许运行命令来操作可编辑区域的内容,注意,是可编辑区域

定义

bool = document.execCommand(aCommandName, aShowDefaultUI, aValueArgument)

方法返回一个 Boolean 值,表示操作是否成功。

  • aCommandName :表示命令名称,比如: copy, cut 等(更多命令见命令);
  • aShowDefaultUI:是否展示用户界面,一般情况下都是 false;
  • aValueArgument:有些命令需要额外的参数,一般用不到;

使用

  1. 从输入框复制
    现在页面上有一个 标签,我们想要复制其中的内容,我们可以这样做:
<input id="demoInput" value="hello world">
<button id="btn">点我复制</button>
const btn = document.querySelector('#btn');
btn.addEventListener('click', () => {
	const input = document.querySelector('#demoInput');
	input.select();
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('复制成功');
	}
})
  1. 其它地方复制
    有的时候页面上并没有 标签,我们可能需要从一个 <div> 中复制内容,或者直接复制变量。
    还记得在 execCommand() 方法的定义中提到,它只能操作可编辑区域,也就是意味着除了 <input><textarea> 这样的输入域以外,是无法使用这个方法的。
    这时候我们需要曲线救国。
<button id="btn">点我复制</button>
const btn = document.querySelector('#btn');
btn.addEventListener('click',() => {
	const ta = document.createElement('textarea');
	// 设置下面的样式为了不影响页面显示
    ta.style.fontSize = '12pt';
    ta.style.border = '0';
    ta.style.padding = '0';
    ta.style.margin = '0';
    ta.style.position = 'absolute';
    ta.style.right = '-9999px';
	document.body.appendChild(ta);
	ta.value = '复制内容'
    //千万不要使用ta.setAttribute('value', '复制内容');
    //
	ta.select();
	if (document.execCommand('copy')) {
		document.execCommand('copy');
		console.log('复制成功');
	}
    document.body.removeChild(ta);
    // 解除引用,释放内存
    ta = undefined;
})
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值