在文章中插入大量无意义内容一不美观,二不便复制,不如使用 js
创建隐藏内容的复制按钮吧。
引入 JS
依次进入 控制台 - 外观 - 设置外观 - 主题自定义扩展
,将以下代码加入到 自定义 HTML 元素拓展 - 标签: head 头部 (meta 元素后)
,也可直接加入到主题对应的 header.php
中的 </head>
标签前。
JavaScript Code
- <script>
- // 创建隐藏内容的复制按钮
- document.addEventListener("DOMContentLoaded", initCopyButton);
- function initCopyButton() {
- const copyButton = {
- load() {
- document.querySelectorAll("cp").forEach((cp) => this.newButton(cp));
- },
- newButton(cp) {
- const lock = "lock";
- if (cp.getAttribute(lock)) return;
- cp.setAttribute(lock, true);
- cp.style.display = "0";
- let text = cp.getAttribute("text");
- text = text[0] === "\n" ? text.slice(1) : text;
- const button = document.createElement("a");
- button.href = "javascript:void(0);";
- button.innerHTML = cp.getAttribute("name");
- button.className = "btn btn-primary";
- button.style.textAlign = "center";
- button.setAttribute("onclick", "__miragesCustomCopyButtonListener(this)");
- window.__miragesCustomCopyButtonListener = (button) => {
- const lock = "lock";
- if (button.getAttribute(lock)) return;
- button.setAttribute(lock, true);
- const originName = button.innerHTML;
- const actionResult = this.copy(text) ? "成功" : "失败";
- button.innerHTML = "复制" + actionResult;
- setTimeout(() => {
- button.innerHTML = originName;
- button.removeAttribute(lock);
- }, 250);
- return false;
- };
- cp.parentNode.insertBefore(button, cp);
- setTimeout(() => (button.style.width = button.getBoundingClientRect().width + "px"), 100);
- },
- copy(text) {
- let result = false;
- const wrapper = document.createElement("div");
- const target = document.createElement("pre");
- target.textContent = text;
- wrapper.style.opacity = "0";
- wrapper.appendChild(target);
- document.body.appendChild(wrapper);
- try {
- const range = document.createRange();
- range.selectNodeContents(target);
- const selection = window.getSelection();
- selection.removeAllRanges();
- selection.addRange(range);
- document.execCommand("copy", false, text);
- selection.removeAllRanges();
- result = true;
- } catch (e) {
- console.log("copy failed.");
- }
- document.body.removeChild(wrapper);
- return result;
- },
- };
- copyButton.load();
- }
- </script>
如果你开启了 PJAX
,可能需要单独加入回调函数。对于本主题,依次进入 控制台 - 外观 - 设置外观 - PJAX(BETA) - PJAX RELOAD
,将 initCopyButton();
添加进入即可。
添加按钮
以 html
形式将以下内容写入文章中,即可创建复制按钮。
- !!!
- <cp name="复制静夜思" text="
- 静夜思
- 床前明月光,疑是地上霜。
- 举头望明月,低头思故乡。
- "></cp>
- !!!
如果你想在代码块的右上角添加复制按钮,请看 另一篇文章。
如有问题请在下方留言,文章转载请注明出处,详细交流请加下方群组!请大佬不要屏蔽文中广告,因为它将帮我分担服务器开支,如果能帮忙点击我将万分感谢。
强调几点:(该留言由系统自动生成!)
1. 请不要刷广告,本站没有流量!
2. 我不回复虚假邮箱,因为回复了你也看不到!
3. 存在必须回复的隐藏内容时,可以直接使用表情框里的阿鲁表情!