code 复制操作

156 阅读1分钟
Vue.directive('copy', {
  inserted(el, binding, vnode, oldVnode) {
    //插入复制功能
    //获取代码片段
    let code = el.querySelector('code')
    console.log(code,'codecodecodecode')
    let pre = document.getElementsByTagName('pre')[0]
    let html = code?.innerHTML
    let copy = document.createElement('div')
    copy.classList.add('hljs-copy')
    copy.innerText = '复制'
    //添加点击事件
    copy.addEventListener('click', () => {
        //创建一个输入框
        let textarea = document.createElement('textarea')
        document.body.appendChild(textarea);
        textarea.style.position = 'absolute'
        textarea.style.left = '-99999px'
        textarea.setAttribute('readonly', 'readonly')
        textarea.value = code.innerText;
        textarea.select();
        if (document.execCommand('copy')) {
            document.execCommand('copy');
            copy.innerText = '复制成功'
        }
        document.body.removeChild(textarea);
    })

    el.appendChild(copy)

    //鼠标移入显示复制按钮
    el.addEventListener('mouseleave', () => {
        copy.innerText = '复制'
        copy.style.display = "none"
    })
    el.addEventListener('mouseover', () => {
        copy.style.display = "block"

    })
  }
})


<div class="hljs-container" style="max-height:400px;overflow:auto" v-copy>
    <highlightjs
      language="javascript"
      :code="detailText"
    />
</div>

import Vue from 'vue'
import 'highlight.js/styles/stackoverflow-light.css'
import 'highlight.js/lib/common'
import hljsVuePlugin from "@highlightjs/vue-plugin"

Vue.use(hljsVuePlugin)

this.detailText = JSON.stringify(text,null, 2)


.hljs-container {
    position: relative;
    font-size: 14px;
    text-align: left;
    box-shadow: 0 10px 30px 0 rgb(0 0 0 / 40%);
    code {
      min-height: 100px;
    }
}
/** 复制样式 */
.hljs-copy {
    position: absolute;
    top: 10px;
    right: 10px;
    display: none;
    padding: 0 10px;
    color: #66a9ff;
    font-size: 10px;
    background-color: #ecf5ff;
    border-radius: 3px;
    cursor: pointer;
}