之前为了隐藏无意义内容写了 Typecho 简单实现点击复制,方式是创建隐藏内容的复制按钮。今天无意间看到某大佬的 JS 代码块复制按钮,发现也是我需要的,于是把它移植到了 Typecho
上,下面就介绍 Mirages
主题的使用步骤,其他主题改改选择器名称就行了。
引入 JS
将以下代码添加到主题 header.php
中的 </head>
标签前,或前往 控制台
- 设置外观
- 主题自定义扩展
,将它添加到 自定义 HTML 元素拓展 - 标签: head 头部 (meta 元素后)
。
JavaScript Code
- <script>
- // 在代码块右上角添加复制按钮
- document.addEventListener('DOMContentLoaded', initCodeCopyButton);
- function initCodeCopyButton() {
- function initCSS(callback) {
- const css = `
- .btn-code-copy {
- position: absolute;
- line-height: .6em;
- top: .2em;
- right: .2em;
- color: rgb(87, 87, 87);
- }
- .btn-code-copy:hover {
- color: rgb(145, 145, 145);
- cursor: pointer;
- }
- `;
- const styleId = btoa('btn-code-copy').replace(/[=+\/]/g, '');
- const head = document.getElementsByTagName('head')[0];
- if (!head.querySelector('#' + styleId)) {
- const style = document.createElement('style');
- style.id = styleId;
- if (style.styleSheet) {
- style.styleSheet.cssText = css;
- } else {
- style.appendChild(document.createTextNode(css));
- }
- head.appendChild(style);
- }
- callback();
- };
- function copyTextContent(source) {
- let result = false;
- const target = document.createElement('pre');
- target.style.opacity = '0';
- target.textContent = source.textContent;
- document.body.appendChild(target);
- try {
- const range = document.createRange();
- range.selectNode(target);
- window.getSelection().removeAllRanges();
- window.getSelection().addRange(range);
- document.execCommand('copy');
- window.getSelection().removeAllRanges();
- result = true;
- } catch (e) { console.log('copy failed.'); }
- document.body.removeChild(target);
- return result;
- };
- function initButton(pre) {
- const code = pre.querySelector('code');
- if (code) {
- const preParent = pre.parentElement;
- const newPreParent = document.createElement('div');
- newPreParent.style = 'position: relative';
- preParent.insertBefore(newPreParent, pre);
- const copyBtn = document.createElement('div');
- copyBtn.innerHTML = 'copy';
- copyBtn.className = 'btn-code-copy';
- copyBtn.addEventListener('click', () => {
- copyBtn.innerHTML = copyTextContent(code) ? 'success' : 'failure';
- setTimeout(() => copyBtn.innerHTML = 'copy', 250);
- });
- newPreParent.appendChild(copyBtn);
- newPreParent.appendChild(pre);
- }
- };
- const pres = document.querySelectorAll('pre');
- if (pres.length !== 0) {
- initCSS(() => pres.forEach(pre => initButton(pre)));
- }
- };
- </script>
如果你开启了 PJAX
,则需单独加入回调函数。对于本主题,依次进入 控制台 - 外观 - 设置外观 - PJAX(BETA) - PJAX RELOAD
,将 initCodeCopyButton();
添加进入即可。
如有问题请在下方留言,文章转载请注明出处,详细交流请加下方群组!请大佬不要屏蔽文中广告,因为它将帮我分担服务器开支,如果能帮忙点击我将万分感谢。
强调几点:(该留言由系统自动生成!)
1. 请不要刷广告,本站没有流量!
2. 我不回复虚假邮箱,因为回复了你也看不到!
3. 存在必须回复的隐藏内容时,可以直接使用表情框里的阿鲁表情!