[Typecho 优化]Typecho 简单实现点击复制
意思就是,显示一个按钮,然后你点击按钮复制隐藏内容,下面放个例子
点击复制这里主要说和我同主题的操作
引入 JS
依次进入 控制台 - 外观 - 设置外观 - 主题自定义扩展,将以下代码加入到 自定义 HTML 元素拓展 - 标签: head 头部 (meta 元素后),也可直接加入到主题对应的 header.php 中的 标签前。
JS 代码
copy
- <script>
- // 创建隐藏内容的复制按钮
- document.addEventListener('DOMContentLoaded', initCopyButton);
- function initCopyButton() {
- const util = {
- newButton: function (cp) {
- cp.style.display = '0';
- let text = cp.getAttribute('text');
- text = text[0] === '\n' ? text.slice(1) : text;
- const button = document.createElement('a');
- button.href = '#'
- button.innerHTML = cp.getAttribute('name');
- button.className = 'btn btn-primary';
- button.onclick = () => {
- const originName = button.innerHTML;
- const actionResult = this.copy(text) ? '成功' : '失败';
- button.innerHTML = '复制' + actionResult;
- setTimeout(() => button.innerHTML = originName, 250);
- return false;
- };
- cp.parentNode.insertBefore(button, cp);
- },
- copy: function (text) {
- let result = false;
- const target = document.createElement('pre');
- target.style.opacity = '0';
- target.textContent = text;
- 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;
- }
- };
- document.querySelectorAll('cp').forEach(cp => util.newButton(cp));
- }
- </script>
如果你开启了 PJAX,可能需要单独加入回调函数。对于本主题,依次进入 控制台 - 外观 - 设置外观 - PJAX (BETA) - PJAX RELOAD,
将 initCopyButton();
添加进入即可。
添加按钮
以 html 形式将以下内容写入文章中,即可创建复制按钮。
HTML 代码
copy
- !!!
- <cp name="复制静夜思" text="
- 静夜思
- 床前明月光,疑是地上霜。
- 举头望明月,低头思故乡。
- "></cp>
- !!!
注意事项
我这个主题如果显示复制成功,但是粘贴是空的,解决办法如下:
- 改 35 行,把
const target = document.createElement('pre');
改成const target = document.createElement('textarea');
也就是pre
改成textarea
转自 LOGIhttps://logi.im/blog/copy-on-btn-click-in-typecho.html
版权声明:文章转载请注明来源,如有侵权请联系删除!
ψ(`∇´)ψ
我用电脑 chrome 试了下不行,猜测你用了其他插件或代码,导致剪切板权限被屏蔽了
我就看你的弄了代码复制按钮,和这个,,,,,,@(泪)
那你把 25 行改一下,把 pre 改成 textarea,从const target = document.createElement('pre');
改成
const target = document.createElement('textarea');
我可以你不行就很迷了
这个改了就可以了,你试试我的,什么原理
可以了,原理我也不知道,难道因为你用的是测试版主题 @(笑尿)
10.30 正式版
我 F12 看到的是 Mirages 7.10.1.DEV1 (20200128A)
你说的主题啊,那是测试版哈哈哈 @(阴险),