使用js纯代码复制文字、复制html(保留p标签的换行)两种方法

Copy content of rich editor using Javascript - Stack Overflowhttps://stackoverflow.com/questions/66227056/copy-content-of-rich-editor-using-javascript

 1. 复制html元素 (支持ie)

注意,这个$0可以是一个html元素,但是必须要在document中,如果是自己clone的元素,则需要先document.body.appendChild(ele), 否则a.addRange()这一步会报错

元素需要复制的内容要设置user-select: text, 不想复制的元素设置user-select:none即可

 (1) 方法一

const e = $0; // 选中一个元素

const r = document.createRange();

const startIndex = 0; // 方法一的设置range
const endIndex = e.childNodes.length;
r.setStart(e, startIndex);
r.setEnd(e, endIndex);

const s = window.getSelection();
s.removeAllRanges();
s.addRange(r);

document.execCommand("copy")

(2)方法二 

const e = $0; // 选中一个元素

const r = document.createRange();

r.selectNodeContents(e) // 方法二的设置range

const s = window.getSelection();
s.removeAllRanges();
s.addRange(r);

document.execCommand("copy")

2. 复制文字,不保留格式,用input框等就可以

 const ele = document.createElement('textarea')
 ele.value = text; // 设置需要复制的文字
 document.body.appendChild(ele)
 ele.style.opacity = 0;
 ele.style.position = 'fixed' // 移动到不可屏幕不可见区域
 ele.style.left = '-99999px'
 ele.select()
 document.execCommand('copy')
 ele.remove() // 别忘了每次复制之后移除元素,否则会有很多无用的dom

 

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值