仅对 markdown 做了优化,未测试其他编辑器
复制功能
添加复制按钮的 css
.cnblogs-markdown pre { position: relative; } .cnblogs-markdown pre>span { position: absolute; top: 0; right: 0; border-radius: 2px; padding: 0 10px; font-size: 12px; background: rgba(0, 0, 0, 0.4); color: #fff; cursor: pointer } .cnblogs-markdown pre>.copyed { background: #67c23a }
先引入复制功能所需要的库
<script src="https://cdn.bootcss.com/clipboard.js/2.0.4/clipboard.min.js"></script>
再使用库
$(function() { if ($("#post-date")[0]) { var pres = $(".cnblogs-markdown pre"); if (pres.length) { pres.each(function() { var t = $(this) .children("code") .text(); var btn = $('<span class="copy">复制</span>').attr( "data-clipboard-text", t ); $(this).prepend(btn); var c = new ClipboardJS(btn[0]); c.on("success", function() { btn.addClass("copyed").text("复制成功"); }); c.on("error", function() { btn.text("复制失败"); }); btn.mouseleave(function() { btn.text("复制").removeClass("copyed"); }); }); } } });