1 添加copy-code.swig
在博客根目录下,输入:
cd themes/next/layout/_third-party/
然后在此文件夹下创建名为copy-code.swig的文件,在此文件中输入以下内容:
{% if theme.codeblock.copy_button.enable %}
<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('{{__("post.copy_button")}}').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 theme.codeblock.copy_button.show_result %}
if(result)$(this).text('{{__("post.copy_success")}}')
else $(this).text('{{__("post.copy_failure")}}')
{% endif %}
$(this).blur()
})).on('mouseleave', function (e) {
var $b = $(this).find('.copy-btn')
setTimeout(function () {
$b.text('{{__("post.copy_button")}}')
}, 300)
}).append(e)
})
</script>
{% endif %}
然后返回上一层目录,即
layout
文件夹下,编辑_layout.swig
,如图:
在图中位置添加:
{% include '_third-party/copy-code.swig' %}
2 添加按钮上显示的语言
进入
themes/next/languages/
目录下,在
zh-CN.yml
中的post
下添加:copy_button: 复制
copy_success: 复制成功
copy_failure: 复制失败
如图:

在
en.yml
中的post
下添加:copy_button: Copy
copy_success: Copied
copy_failure: Copy failed
3 在主题配置文件中添加开关
编辑
主题配置文件
(themes/next/_config.yml
),在其中的codeblock
中添加copy_button
的开关,如图所示:
添加的内容为:
# Add copy button on codeblock
copy_button:
enable: true
# Show text copy result
show_result: true
好了,现在退到博客根目录,输入hexo cl && hexo g重新生成一下来查看效果吧~