给 hexo 博客文章中的代码块添加一个一键复制功能
2021/04/17
hexo 5.3.0 next 7.8.0版直接跳到 添加开关 这一步
版本
hexo版本 4.2.1
next版本5.1.4
修改 _layout.swig 文件
进入 hexo/themes/next/layout 目录下
在 _layout.swig 文件中添加下面一行高亮代码(不包括+):
| 12
 3
 4
 5
 6
 7
 8
 
 |   </div>...
 {% include '_third-party/scroll-cookie.swig' %}
 {% include '_third-party/exturl.swig' %}
 ...
 + {% include '_third-party/copy-code.swig' %}
 </body>
 </html>
 
 | 
创建 copy-code.swig 文件
进入 hexo/themes/next/layout/_third-party 目录下
创建一个名为 copy-code.swig 的文件并添加:
| 12
 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
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 
 | {% 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 %}
 
 | 
添加复制按钮显示的语言
假设 hexo/ 目录下的站点配置文件 _config.yml 中的语言配置为 language: zh-Hans
则打开 /themes/next/languages/zh-Hans.yml 文件,在 post 内添加:
| 12
 3
 
 | copy_button: 复制copy_success: 复制成功
 copy_failure: 复制失败
 
 | 
注意前面要留有 两个 空格
添加开关
在 hexo/themes/next/_config.yml 文件中修改:
| 12
 3
 4
 5
 6
 
 | # Add copy button on codeblockcodeblock:
 copy_button:
 enable: true
 # Show text copy result
 show_result: true
 
 | 
来源