最近在奋斗PAT,想把做出来的题目以及过程放到个人博客上,我希望能够实现像PAT网站中那样输入样例和输出样例能够复制粘贴的同时代码也要能够复制粘贴,一开始通过将输入样例与输出样例放到代码块中,但是,出现了前面带序号的问题。
我的需求是:代码能够复制但是需要显示序号,便于查看。输入输出能够复制,但是不需要显示序号。
做到如图的效果分为以下三步:

  • 代码前添加序号
  • 代码区域添加剪贴板
  • note区域添加剪贴板

代码前添加序号

HEXO官方文档中:

代码开关

存在代码高亮和序号的设置,我们通过根目录打开站点配置文件_config.yml,在约47行左右会找到如下代码:

highlight:
  enable: true
  line_number: true
  auto_detect: true
  tab_replace: ''
  wrap: true
  hljs: false

line_number设置为ture即可。

代码区域添加剪贴板

参考Felix大佬的文章:Hexo-Next搭建个人博客(代码块复制功能)

note区域添加剪贴板

假设已经看完了代码区域添加剪贴板,还需要了解一下Next的内置标签有关note标签的部分
接下来进行最后一步,在note中添加剪贴板,具体操作如下:
由于note区域与代码区域的样式不同,因此需要设定note部分的css,在.\themes\next\source\css\_custom\custom.styl后添加CSS代码:

.note-copy {
    display: inline-block;
    cursor: pointer;
    background-color: transparent;
    border: none;
    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;
    color: #222;
    -webkit-transition: opacity .3s ease-in-out;
    -o-transition: opacity .3s ease-in-out;
    transition: opacity .3s ease-in-out;
    padding: 2px 6px;
    position: absolute;
    right: 15px;
    top: 15px;
    opacity: 0;
}
.note-copy span {
    margin-left: 5px;
}
.note:hover .note-copy{
  opacity: 1;
}

之后在.\themes\next\source\js\src\clipboard-use.js中替换为如下代码:

/*页面载入完成后,创建复制按钮*/
!function (e, t, a) {
    /* code */
    var initCopyCode = function () {
        var copyHtml = '';
        copyHtml += '<button class="btn-copy" data-clipboard-snippet="">';
        //fa fa-globe可以去字体库替换自己想要的图标
        copyHtml += '  <i class="fa fa-clipboard"></i><span>复制</span>';
        copyHtml += '</button>';
        $(".highlight .code pre").before(copyHtml);
        new ClipboardJS('.btn-copy', {
            target: function (trigger) {
                return trigger.nextElementSibling;
            }
        });
        var notecopy = '';
        notecopy += '<button class="note-copy" data-clipboard-snippet="">';
        //fa fa-globe可以去字体库替换自己想要的图标
        notecopy += '  <i class="fa fa-clipboard"></i><span>复制</span>';
        notecopy += '</button>';
        
        $(".note").prepend(notecopy);
        new ClipboardJS('.note-copy', {
            target: function (trigger) {
                return trigger.nextElementSibling;
            }
        });
    }
    initCopyCode();
}(window, document);

通过修改这两部分即可实现所需要的效果。
如果markdown文件中存在多种标签,那么需要将这些标签放入<div>中。
即:

{% note primary %}
<div>
<h1>h1</h1>
<b>b</b>    
</div>
{% endnote %}