87 lines
3.4 KiB
JavaScript
87 lines
3.4 KiB
JavaScript
(function() {
|
|
const initShare = () => {
|
|
const shareBtn = document.getElementById('share-btn');
|
|
const sharePanel = document.getElementById('share-panel');
|
|
const copyBtn = document.getElementById('copy-link');
|
|
const shareContainer = document.getElementById('share-component');
|
|
const closeBtn = document.getElementById('close-share');
|
|
|
|
if (!shareBtn || !sharePanel) return;
|
|
|
|
// 1. 处理分享主按钮
|
|
shareBtn.addEventListener('click', async (e) => {
|
|
e.preventDefault();
|
|
e.stopPropagation();
|
|
|
|
const shareData = {
|
|
title: document.title,
|
|
url: window.location.href
|
|
};
|
|
|
|
// 原生分享触发条件:浏览器支持 + 必须是 HTTPS 环境
|
|
if (navigator.share && window.isSecureContext) {
|
|
try {
|
|
await navigator.share(shareData);
|
|
return; // 成功唤起系统分享,不再向下执行
|
|
} catch (err) {
|
|
// 如果不是用户主动取消(AbortError),则打印错误并在下方降级处理
|
|
if (err.name !== 'AbortError') console.error('Share failed:', err);
|
|
}
|
|
}
|
|
|
|
// 降级方案:显示自定义 HTML 分享面板
|
|
sharePanel.classList.toggle('hidden');
|
|
});
|
|
|
|
// 2. 处理链接复制
|
|
copyBtn.addEventListener('click', (e) => {
|
|
e.preventDefault();
|
|
const currentUrl = window.location.href;
|
|
|
|
navigator.clipboard.writeText(currentUrl).then(() => {
|
|
const iconBg = document.getElementById('copy-icon-bg');
|
|
const copySvg = document.getElementById('copy-svg');
|
|
const checkSvg = document.getElementById('check-svg');
|
|
const copyText = document.getElementById('copy-text');
|
|
|
|
// 成功反馈状态
|
|
iconBg.classList.replace('bg-slate-100', 'bg-green-500');
|
|
iconBg.classList.replace('text-slate-600', 'text-white');
|
|
copySvg.classList.add('hidden');
|
|
checkSvg.classList.remove('hidden');
|
|
copyText.innerText = '已复制';
|
|
|
|
setTimeout(() => {
|
|
iconBg.classList.replace('bg-green-500', 'bg-slate-100');
|
|
iconBg.classList.replace('text-white', 'text-slate-600');
|
|
copySvg.classList.remove('hidden');
|
|
checkSvg.classList.add('hidden');
|
|
copyText.innerText = '复制';
|
|
}, 2000);
|
|
}).catch(() => {
|
|
alert('复制失败,请手动复制地址栏链接');
|
|
});
|
|
});
|
|
|
|
// 3. 面板交互控制
|
|
const closePanel = () => sharePanel.classList.add('hidden');
|
|
|
|
// 点击关闭按钮隐藏
|
|
if (closeBtn) closeBtn.addEventListener('click', closePanel);
|
|
|
|
// 点击页面其他地方隐藏
|
|
document.addEventListener('click', (e) => {
|
|
if (!shareContainer.contains(e.target)) closePanel();
|
|
});
|
|
|
|
// 阻止面板内部点击触发隐藏
|
|
sharePanel.addEventListener('click', (e) => e.stopPropagation());
|
|
};
|
|
|
|
// 确保 DOM 加载后运行
|
|
if (document.readyState === 'loading') {
|
|
document.addEventListener('DOMContentLoaded', initShare);
|
|
} else {
|
|
initShare();
|
|
}
|
|
})(); |