[fix] error handler for codeCopyBtn (#419)

This commit is contained in:
纸鹿/Zhilu 2024-04-01 16:44:55 +08:00 committed by GitHub
parent 47b10e1105
commit 373948c28e
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
1 changed files with 27 additions and 36 deletions

View File

@ -1,41 +1,32 @@
window.codeElements.forEach(code => { window.codeElements.forEach((codeElement) => {
// copy btn // 创建复制按钮
const codeCopyBtn = document.createElement('div'); const codeCopyBtn = document.createElement('div');
codeCopyBtn.classList.add('copy-btn'); codeCopyBtn.className = 'copy-btn';
codeCopyBtn.innerHTML = ctx.copycode.default_text; codeCopyBtn.textContent = ctx.copycode.default_text;
code.appendChild(codeCopyBtn); codeElement.appendChild(codeCopyBtn);
codeCopyBtn.addEventListener('click', async () => {
const currentCodeElement = code.children[0]?.innerText;
await copyCode(currentCodeElement);
codeCopyBtn.innerHTML = ctx.copycode.success_text;
codeCopyBtn.classList.add('success');
hud.toast(ctx.copycode.toast, 2500);
setTimeout(() => {
codeCopyBtn.innerHTML = ctx.copycode.default_text;
codeCopyBtn.classList.remove('success');
},3000);
})
})
async function copyCode(currentCode) { // 添加点击事件监听
if (navigator.clipboard) { codeCopyBtn.addEventListener('click', async () => {
try { const codeToCopy = codeElement.querySelector('code')?.textContent || '';
await navigator.clipboard.writeText(currentCode); if (navigator.clipboard) {
} catch (error) { try {
// 未获得用户许可 await navigator.clipboard.writeText(codeToCopy);
codeCopyBtn.innerText = '未获得用户许可'; codeCopyBtn.textContent = ctx.copycode.success_text;
codeCopyBtn.classList.add('success');
hud.toast(ctx.copycode.toast, 2500);
} catch (error) {
codeCopyBtn.textContent = '未获得用户许可';
codeCopyBtn.classList.add('warning');
}
} else {
codeCopyBtn.textContent = '浏览器不支持/非HTTPS';
codeCopyBtn.classList.add('warning'); codeCopyBtn.classList.add('warning');
setTimeout(() => {
codeCopyBtn.innerText = ctx.copycode.default_text;
codeCopyBtn.classList.remove('warning');
},3000);
} }
} else {
codeCopyBtn.innerText = '当前浏览器不支持此api'; // 3秒后恢复默认文本
codeCopyBtn.classList.add('warning');
setTimeout(() => { setTimeout(() => {
codeCopyBtn.innerText = ctx.copycode.default_text; codeCopyBtn.textContent = ctx.copycode.default_text;
codeCopyBtn.classList.remove('warning'); codeCopyBtn.classList.remove('success', 'warning');
},3000); }, 3000);
} });
} });