实现原理
动态的创建input标签,把要复制的内容赋值给input的value属性,然后调用input 的select方法选中文字,document的execCommand 方法,最后移除input标签。
注意!!!
必须将动态创建的input标签插入页面中,否则将复制失败。
话不多说上代码👀
const setClipBoardData = () => {
const input = document.createElement('input');
input.value = '床前明月光,疑是地上霜。';
input.style.opacity = 0;
document.body.appendChild(input);
input.select();
document.execCommand('copy');
input.remove()
}