技术文章里怎么能没有代码复制功能,一键复制是多么提高效率的一件事啊。本文就将教你给博客添加代码复制这个功能。
前言
本人使用的是Hexo的NexT主题,NexT版本为v6.1。事实上,在NexT主题的v6.3版本里已经加入了代码复制这个功能,所以如果你刚开始使用NexT,直接升级主题,并在主题配置文件中打开代码复制的开关就好了。
因为本人对此NexT主题已经改动了不少源码,升级的话会很麻烦,所以便考虑自己加入这个功能。好了,废话不多说了,开始正题。
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
重新生成一下来查看效果吧~
评论区