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;
}