1.复制文本【安全环境下-localhost或者https】
<button class="btn" onclick="copy1()">复制文本</button>
function copy1() {
navigator.clipboard.writeText('普通')
}
2.复制文本【所有环境都可用】
function copy(val){
const textarea = document.createElement('textarea');
textarea.value = val;
document.body.appendChild(textarea);
textarea.select();
try {
const successful = document.execCommand('copy');
console.log("复制成功")
} catch (err) {
console.error('复制失败:', err);
} finally {
document.body.removeChild(textarea);
}
},
以下为复制markdown代码或者图片功能,我自己写的ChatGPT网站也用了以下功能,
演示地址为:演示地址
3.复制markdown语法
copyWord(val) {
const el = document.createElement('div');
el.innerHTML = marked(val);
el.contentEditable = 'true';
this.removeBorderStyles(el);
document.body.appendChild(el);
const range = document.createRange();
range.selectNodeContents(el);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
document.execCommand('copy');
selection.removeAllRanges();
document.body.removeChild(el);
this.$Message.success('复制成功!');
},
- 1
- 2
- 3
- 4
- 5
- 6
- 7
- 8
- 9
- 10
- 11
- 12
- 13
- 14
- 15
- 16
- 17
- 18
- 19
- 20
- 21