js 实现分享功能实现
使用Web Share API实现分享功能
Web Share API是浏览器原生提供的分享接口,支持分享文本、链接等内容到用户设备上的其他应用(如社交媒体、邮件等)。该方法仅适用于HTTPS环境或本地开发环境(localhost)。
if (navigator.share) {
navigator.share({
title: '分享标题',
text: '分享内容描述',
url: 'https://example.com'
})
.catch(error => console.log('分享失败:', error));
} else {
console.log('浏览器不支持Web Share API');
}
自定义弹窗实现分享功能
对于不支持Web Share API的浏览器,可以通过自定义弹窗实现分享功能。以下代码示例展示如何通过点击按钮触发分享弹窗:
document.getElementById('share-btn').addEventListener('click', function() {
// 创建分享弹窗元素
const shareDialog = document.createElement('div');
shareDialog.innerHTML = `
<div class="share-dialog">
<p>分享到:</p>
<a href="https://twitter.com/share?url=${encodeURIComponent(window.location.href)}" target="_blank">Twitter</a>
<a href="https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(window.location.href)}" target="_blank">Facebook</a>
<a href="https://wa.me/?text=${encodeURIComponent(window.location.href)}" target="_blank">WhatsApp</a>
</div>
`;
// 添加样式和关闭功能
shareDialog.style.position = 'fixed';
shareDialog.style.top = '50%';
shareDialog.style.left = '50%';
shareDialog.style.transform = 'translate(-50%, -50%)';
shareDialog.style.padding = '20px';
shareDialog.style.background = 'white';
shareDialog.style.boxShadow = '0 0 10px rgba(0,0,0,0.2)';
// 点击外部关闭弹窗
shareDialog.addEventListener('click', function(e) {
if (e.target === shareDialog) {
document.body.removeChild(shareDialog);
}
});
document.body.appendChild(shareDialog);
});
使用第三方库实现分享功能
对于更复杂的分享需求,可以使用第三方库如share-this或social-share.js。以下是使用share-this库的示例:
安装库:
npm install share-this
使用示例:
import shareThis from 'share-this';
import shareThisTwitter from 'share-this/dist/sharers/twitter';
import shareThisFacebook from 'share-this/dist/sharers/facebook';
const share = shareThis({
sharers: [shareThisTwitter, shareThisFacebook]
});
share.init();
复制链接到剪贴板功能
实现点击按钮复制当前页面URL到剪贴板的功能:
document.getElementById('copy-btn').addEventListener('click', function() {
navigator.clipboard.writeText(window.location.href)
.then(() => alert('链接已复制!'))
.catch(err => console.error('复制失败:', err));
});
社交媒体平台专用分享URL
各主流社交媒体平台提供专用分享URL格式,可直接在链接中指定分享内容:
- Twitter:
https://twitter.com/intent/tweet?text=${encodeURIComponent(text)}&url=${encodeURIComponent(url)} - Facebook:
https://www.facebook.com/sharer/sharer.php?u=${encodeURIComponent(url)} - LinkedIn:
https://www.linkedin.com/shareArticle?mini=true&url=${encodeURIComponent(url)}&title=${encodeURIComponent(title)} - WhatsApp:
https://wa.me/?text=${encodeURIComponent(text + ' ' + url)} - Email:
mailto:?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}







