先贴代码,Button是antd-design中的button,要做到的是点击button复制span中的内容。
toClipboard = () => {
const copySpan = document.getElementById('copy');
const range = document.createRange();
range.selectNodeContents(copySpan);
const selection = window.getSelection();
selection.removeAllRanges();//(注意)
selection.addRange(range);
const copyContent = document.execCommand('Copy',false,null);
selection.removeRange(range);
if (copyContent) {
console.log('复制成功', copyContent);
}
}
<Button key="copyButton" onClick={this.toClipboard} >
复制
</Button>
<span id="copy">{JSON.stringify(data)}</span>
这里用到的是浏览器的一个api来实现复制功能: document.execCommand('Copy',false,null);
实现步骤:
- 首先是利用
document.createRange()
创建一个 Range 对象 ,然后获取所需复制元素的子元素的长度大小,我这里使用的是selectNodeContents()
方法,来选择区域的大小,还可以调用Range的其他方法,如:setStart,set