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:有些命令需要额外的参数,一般用不到;
使用
- 从输入框复制
现在页面上有一个 标签,我们想要复制其中的内容,我们可以这样做:
<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('复制成功');
}
})
- 其它地方复制
有的时候页面上并没有 标签,我们可能需要从一个 <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;
})