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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)