文本选择分享按钮JS代码需求及WhatsApp按钮失效问题求助
问题根源
你代码里的documentMouseDown函数逻辑存在问题:当点击其中一个分享按钮时,另一个按钮的判断条件event.target.id !== "xxx-share-btn"会成立,进而执行window.getSelection().empty()清空文本选择。而浏览器事件触发顺序是mousedown先于click,所以当按钮的click事件执行时,选中的文本已经被清空,分享逻辑自然无法运行,同时还会导致按钮状态异常。
修复方案
修改documentMouseDown函数,只有当点击的不是两个分享按钮时,才处理隐藏按钮和清空选择的逻辑:
function documentMouseDown(event) { // 判断点击的是否是任意一个分享按钮 const isShareBtn = event.target.id === "twitter-share-btn" || event.target.id === "whatsapp-share-btn"; if (!isShareBtn) { // 隐藏Twitter按钮 if (getComputedStyle(twitterShareBtn).display === "block") { twitterShareBtn.style.display = "none"; twitterShareBtn.classList.remove("btnEntrance"); } // 隐藏WhatsApp按钮 if (getComputedStyle(whatsappShareBtn).display === "block") { whatsappShareBtn.style.display = "none"; whatsappShareBtn.classList.remove("btnEntrance"); } // 清空选择 window.getSelection().empty(); } }
额外优化建议
- 合并重复的CSS样式,减少冗余代码:
#twitter-share-btn, #whatsapp-share-btn { width: 40px; height: 2.5rem; font-size: 1.25rem; color: #ffffff; background-color: rgb(0, 0, 0); cursor: pointer; border: 2px solid #868686; border-radius: 50%; position: absolute; top: 0; left: 0; z-index: 10; display: none; transition: color 0.2s, background-color 0.2s ease-in-out; } #twitter-share-btn:hover { background-color: #56b8f5; } #whatsapp-share-btn:hover { background-color: #25d366; /* 替换为WhatsApp品牌绿色更贴合视觉 */ } #twitter-share-btn i, #whatsapp-share-btn i { pointer-events: none; } .btnEntrance { animation-duration: 0.2s; animation-fill-mode: both; animation-name: btnEntrance; }
- 分享链接中的文本无需额外添加双引号,
encodeURIComponent已处理特殊字符,优化后的分享代码:
// Twitter分享函数修改 function twitterShareBtnClick(event) { const selectedText = window.getSelection().toString().trim(); if (selectedText.length) { const twitterShareUrl = "https://twitter.com/intent/tweet"; const text = encodeURIComponent(selectedText); const currentUrl = encodeURIComponent(window.location.href); const hashtags = "helloworld, test, testing"; const via = "CodingJrney"; window.open(`${twitterShareUrl}?text=${text}&url=${currentUrl}&hashtags=${hashtags}&via=${via}`); } } // WhatsApp分享函数修改 function whatsappShareBtnClick(event) { const selectedText1 = window.getSelection().toString().trim(); if (selectedText1.length) { const whatsappShareUrl = "https://api.whatsapp.com/send"; const text = encodeURIComponent(selectedText1); window.open(`${whatsappShareUrl}?text=${text}`); } }
内容的提问来源于stack exchange,提问作者OwO 1234
相关产品推荐
相关产品推荐

