hexo笔记十四:next主题添加代码块一键复制功能

next6.3的版本中,直接在主题配置文件的相应位置设置为true即可。

本文在next5.1.4的版本上进行操作。

1 在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 %}

2 编辑themes/next/layout/_layout.swig文件,在文件末尾的如下位置添加一行代码:

在这里插入图片描述

{% include '_third-party/copy-code.swig' %}

3 添加按钮上显示的语言

themes/next/languages/zh-CN.yml文件的post板块中添加下列代码:
在这里插入图片描述

copy_button: 复制
copy_success: 复制成功
copy_failure: 复制失败

4 在主题配置文件themes/next/_config.yml中添加开关

在这里插入图片描述
需要注意的是,nextv5.1.4的版本是没有codeblock选项的,则直接在配置文件中添加即可。一定要顶格写(如上图),否则不会生效。

codeblock:
  border_radius:
  copy_button:
    enable: true
    # Show text copy result
    show_result: true

5 重新生成

hexo g

猜你喜欢

转载自blog.csdn.net/Awt_FuDongLai/article/details/107466848