document.execCommand('copy')使用

编程入门 行业动态 更新时间:2024-10-17 20:32:06

<a href=https://www.elefans.com/category/jswz/34/1767506.html style=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. 坑1:复制时想保留换行,input不会保留换行,换成textarea后成功
  2. 坑2:换成textarea后使用setAttribute('value','')复制失败,换成textarea.value后成功
  3. 坑3:复制时想保留value里的换行,尝试\r\n<br/>\r后发现使用\r成功

更多推荐

document.execCommand('copy')使用

本文发布于:2024-02-25 16:48:06,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1699655.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:document   execCommand   copy

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!