前端实现页面文本复制/代码复制/mardown复制的几种方式

324 阅读1分钟

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);// 'marked'是一个Markdown到HTML的转换库
            el.contentEditable = 'true'; 
            //q:为什么要设置contentEditable为true?
            //a:因为如果不设置为true,那么在Firefox中,el.innerHTML = '<table><tr><td>1</td></tr></table>'会变成'<table><tbody><tr><td>1</td></tr></tbody></table>',这会导致Word无法识别
        
            // 清除或调整样式以避免在Word中出现边框
            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('复制成功!');
        },