此方法对所有没有代码块复制功能的主题都有效,基于 https://github.com/zenorocha/clipboard.js 实现
下载 clipboard.js
下载第三方插件:clipboard.js
保存文件到 theme/xxx/source/js 下。
然后在 theme/xxx/source/js 目录下,创建 clipboard-use.js,添加内容如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
| !function (e, t, a) { var initCopyCode = function(){ var copyHtml = ''; copyHtml += '<button class="btn-copy" data-clipboard-snippet="">'; copyHtml += '<span>复制</span>'; copyHtml += '</button>'; $(".highlight .code pre").before(copyHtml); new ClipboardJS('.btn-copy', { target: function(trigger) { return trigger.nextElementSibling; } }); } initCopyCode(); }(window, document);
|
在 theme/xxx/source/css/style.css 样式中添加如下代码:
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{ //方便copy代码按钮(btn-copy)的定位 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; color: #333; -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: 5px; top: 5px; opacity: 0; } .btn-copy span { margin-left: 5px; } .highlight:hover .btn-copy{ opacity: 1; }
|
引用js文件
将以下代码加入到 /body
之前:
1 2 3
| <!-- 代码块复制功能 --> <script type="text/javascript" src="/js/clipboard.min.js"></script> <script type="text/javascript" src="/js/clipboard-use.js"></script>
|
或者将 clipboard.min.js 和 clipboard-use.js 保存到CDN上,通过远程引用也可以