document.execCommand('copy')使用"/>
document.execCommand('copy')使用
js实现复制到粘贴板
写财务处工具集时有一个基本账户:纳税号想要和淘宝一样的一键复制功能;
html代码
因为不想显示输入框,所以只写了一个button
<button id="btn" style="margin-top: 40px;">一键复制</button>
js代码
const btn = document.querySelector('#btn');btn.addEventListener('click', () => {const textarea= document.createElement('textarea');textarea.setAttribute('readonly', 'readonly');textarea.value = '姓名:肖敏\r性别:女\r年龄:23';document.body.appendChild(textarea);textarea.select();if (document.execCommand('copy')) {document.execCommand('copy');alert('复制成功');}document.body.removeChild(textarea);})
- 坑1:复制时想保留换行,
input
不会保留换行,换成textarea
后成功 - 坑2:换成
textarea
后使用setAttribute('value','')
复制失败,换成textarea.value
后成功 - 坑3:复制时想保留value里的换行,尝试
\r\n
,<br/>
,\r
后发现使用\r
成功
更多推荐
document.execCommand('copy')使用
发布评论