Hexo Next 代码块复制功能
在NexT主题的v6.3版本里已经加入了代码复制这个功能,所以如果你刚开始使用NexT,直接升级主题,并在主题配置文件中打开代码复制的开关就好了,如果版本低于6.3你可以参考以下方式自行添加。
使用方法
在 .\themes\next\source\js\src
目录下新建 clipboard-use.js
文件内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22
| !function (e, t, a) { var initCopyCode = function(){ var copyHtml = ''; copyHtml += '<button class="btn-copy" data-clipboard-snippet="">'; copyHtml += ' <i class="fa fa-globe"></i><span>copy</span>'; copyHtml += '</button>'; $(".highlight").wrap($('<div class="highlight-wrap"></div>')); $('.highlight-wrap').prepend(copyHtml); var clipboard = new ClipboardJS('.btn-copy', { target: function(trigger) { return trigger.nextElementSibling; } }); clipboard.on('success', function(e) { toastPlug('复制成功!', 2000) }); } initCopyCode(); }(window, document);
|
设置复制按钮样式
在 .\themes\next\source\css\_custom\custom.styl
样式文件中添加下面代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| .highlight-wrap{ position: relative; } .btn-copy { display: inline-block; cursor: pointer; background-color: #eee; background-image: linear-gradient(#fcfcfc,#eee); border: 1px solid #d5d5d5; border-radius: 3px; -webkit-user-select: none; -moz-user-select: none; -ms-user-select: none; user-select: none; -webkit-appearance: none; font-size: 13px; font-weight: 700; line-height: 20px; outline: none; color: #333; -webkit-transition: opacity .5s ease-in-out; -o-transition: opacity .5s ease-in-out; transition: opacity .5s ease-in-out; padding: 2px 6px; position: absolute; right: 7px; top: 7px; opacity: 0; } .btn-copy span { margin-left: 5px; } .highlight-wrap:hover .btn-copy{ opacity: 1; }
|
引入文件
在 .\themes\next\layout\_layout.swig
文件中,添加引用(注:在 swig 末尾或 body 结束标签()之前添加)
1 2 3
| <script type="text/javascript" src="/js/src/clipboard.min.js"></script> <script type="text/javascript" src="/js/src/clipboard-use.js"></script>
|
注:一开始找的添加复制按钮代码,有一点小bug,如果代码块部分内容超出有横向滑动,复制按钮copy就会跟着移动,而不能固定在右上角,此时只需要将复制按钮和highlight
部分外层包裹一个元素,设置position:relative
即可。
v6.3版本(及以上)添加复制的办法
打开.\themes\next\_config.yml
,找到
1 2 3 4 5
| copy_button: enable: true
style:
|
把copy_button
设置为true
即可