全站通知:
Widget:SyntaxhighlightCopy
刷
历
编
跳到导航
跳到搜索
为Syntaxhighlight标签右上角添加复制按钮。代码完全由AI生成。
使用方式:
1. 为 syntaxhighlight 添加 class="copy"
2. 引入Widget {{#Widget:SyntaxhighlightCopy}}
代码:
(function () {
'use strict';
function runOnDOMReady(fn){ document.readyState==='loading' ? document.addEventListener('DOMContentLoaded', fn) : fn(); }
function qsa(sel, root){ return Array.from((root||document).querySelectorAll(sel)); }
function copyToClipboard(text){
if (navigator.clipboard && window.isSecureContext) {
return navigator.clipboard.writeText(text).then(()=>true, ()=>false);
}
const ta = document.createElement('textarea');
ta.value = text; ta.style.cssText = 'position:fixed;opacity:0;pointer-events:none;';
document.body.appendChild(ta); ta.select();
let ok = false; try { ok = document.execCommand('copy'); } catch(e){}
ta.remove(); return Promise.resolve(ok);
}
runOnDOMReady(function(){
qsa('div.copy.mw-highlight').forEach(function(block){
if (!block || block.querySelector('.bwiki-copy-btn')) return;
if (getComputedStyle(block).position === 'static') block.style.position = 'relative';
const btn = document.createElement('button');
btn.className = 'bwiki-copy-btn';
btn.textContent = '复制';
btn.title = '点击复制代码';
btn.style.cssText = 'position:absolute;top:8px;right:8px;z-index:10;padding:4px 8px;font-size:12px;background:#36c;color:#fff;border:none;border-radius:3px;cursor:pointer;opacity:.85;transition:opacity .2s';
btn.onmouseenter = function(){ this.style.opacity = '1'; };
btn.onmouseleave = function(){ this.style.opacity = '.85'; };
btn.onclick = function(){
const pre = block.querySelector('pre');
const text = pre ? (pre.textContent||'').trim() : '';
const restore = (label,bg)=>{ const oldT=btn.textContent, oldB=btn.style.background; btn.textContent=label; btn.style.background=bg; setTimeout(()=>{ btn.textContent=oldT; btn.style.background=oldB; }, 1600); };
copyToClipboard(text).then(ok => ok ? restore('已复制!', '#0a5') : restore('复制失败', '#d33'));
};
block.appendChild(btn);
});
});
})();