版权声明:本文为作者原创,转载请注明出处,联系qq:32248827 https://blog.csdn.net/dataiyangu/article/details/88879328
广告:
本人博客地址:https://mmmmmm.me
源码:https://github.com/dataiyangu/dataiyangu.github.io
一个将csdn文章转为hexo支持的文章格式的小东西:https://github.com/dataiyangu/csdn2hexo
自己的方式
在博客根目录下,输入:
cd themes/next/layout/_third-party/
然后在此文件夹下创建名为copy-code.swig的文件,在此文件中输入以下内容:
<style>
.copy-btn {
display: inline-block;
padding: 6px 12px;
font-size: 13px;
font-weight: 700;
line-height: 20px;
color: #333;
white-space: nowrap;
vertical-align: middle;
cursor: pointer;
background-color: #eee;
background-image: linear-gradient(#fcfcfc, #eee);
border: 1px solid #d5d5d5;
border-radius: 3px;
user-select: none;
outline: 0;
}
.highlight-wrap .copy-btn {
transition: opacity .3s ease-in-out;
opacity: 0;
padding: 2px 6px;
position: absolute;
right: 4px;
top: 8px;
}
.highlight-wrap:hover .copy-btn,
.highlight-wrap .copy-btn:focus {
opacity: 1
}
.highlight-wrap {
position: relative;
}
</style>
<script>
$('.highlight').each(function (i, e) {
var $wrap = $('<div>').addClass('highlight-wrap')
$(e).after($wrap)
$wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function (e) {
var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
return $(e).text()
}).toArray().join('\n')
var ta = document.createElement('textarea')
document.body.appendChild(ta)
ta.style.position = 'absolute'
ta.style.top = '0px'
ta.style.left = '0px'
ta.value = code
ta.select()
ta.focus()
var result = document.execCommand('copy')
document.body.removeChild(ta)
if(result)$(this).text('复制成功')
else $(this).text('复制失败')
$(this).blur()
})).on('mouseleave', function (e) {
var $b = $(this).find('.copy-btn')
setTimeout(function () {
$b.text('复制')
}, 300)
}).append(e)
})
</script>
然后返回上一层目录,即layout文件夹下,编辑_layout.swig,如图:
添加
{% include '_third-party/copy-code.swig' %}
注意我加入了pjax,这句话不要放在pjax的container中
另外在自己的pjax文件中加入
//复制js
function copy_code(){
$('.highlight').each(function (i, e) {
var $wrap = $('<div>').addClass('highlight-wrap')
$(e).after($wrap)
$wrap.append($('<button>').addClass('copy-btn').append('复制').on('click', function (e) {
var code = $(this).parent().find('.code').find('.line').map(function (i, e) {
return $(e).text()
}).toArray().join('\n')
var ta = document.createElement('textarea')
document.body.appendChild(ta)
ta.style.position = 'absolute'
ta.style.top = '0px'
ta.style.left = '0px'
ta.value = code
ta.select()
ta.focus()
var result = document.execCommand('copy')
document.body.removeChild(ta)
if(result)$(this).text('复制成功')
else $(this).text('复制失败')
$(this).blur()
})).on('mouseleave', function (e) {
var $b = $(this).find('.copy-btn')
setTimeout(function () {
$b.text('复制')
}, 300)
}).append(e)
})
}
感谢
https://qiming.info/about/
这个作者充分的了解了hexo的机制应该,通过配置的方法,我自己不太需要配置,所以做了点小小的改动