Js实现划词翻译
实现划词翻译的基本思路
划词翻译的核心是监听用户鼠标选中文本的事件,获取选中内容后调用翻译API,最后以弹窗等形式展示翻译结果。以下是具体实现方法:
监听文本选中事件
通过mouseup事件监听用户鼠标释放动作,结合window.getSelection()获取选中文本:
document.addEventListener('mouseup', function(e) {
const selection = window.getSelection();
const selectedText = selection.toString().trim();
if (selectedText.length > 0) {
// 后续处理逻辑
}
});
调用翻译API
可以使用免费翻译API如Google Translate或百度翻译API。以下是使用百度翻译API的示例(需提前申请API key):
function translateText(text, callback) {
const appid = 'YOUR_APP_ID'; // 替换为实际ID
const key = 'YOUR_SECRET_KEY'; // 替换为实际密钥
const salt = Date.now();
const sign = md5(appid + text + salt + key); // 需要实现MD5哈希
fetch(`https://fanyi-api.baidu.com/api/trans/vip/translate?q=${encodeURIComponent(text)}&from=en&to=zh&appid=${appid}&salt=${salt}&sign=${sign}`)
.then(response => response.json())
.then(data => callback(data.trans_result[0].dst));
}
显示翻译结果
创建悬浮窗显示翻译结果,使用CSS定位到鼠标位置:
function showTranslation(text, x, y) {
let popup = document.getElementById('translation-popup');
if (!popup) {
popup = document.createElement('div');
popup.id = 'translation-popup';
popup.style.cssText = 'position:absolute;background:#fff;padding:8px;border:1px solid #ddd;z-index:9999;';
document.body.appendChild(popup);
}
popup.textContent = text;
popup.style.left = `${x}px`;
popup.style.top = `${y + 20}px`;
popup.style.display = 'block';
}
完整代码整合
将各部分逻辑整合,注意添加防抖处理和事件委托:
document.addEventListener('mouseup', debounce(function(e) {
const selection = window.getSelection();
const text = selection.toString().trim();
if (text.length > 0) {
translateText(text, function(translated) {
showTranslation(translated, e.clientX, e.clientY);
});
}
}, 300));
function debounce(fn, delay) {
let timer;
return function() {
clearTimeout(timer);
timer = setTimeout(() => fn.apply(this, arguments), delay);
};
}
样式优化建议
为悬浮窗添加CSS样式提升用户体验:
#translation-popup {
max-width: 300px;
box-shadow: 0 2px 10px rgba(0,0,0,0.2);
border-radius: 4px;
font-size: 14px;
line-height: 1.5;
animation: fadeIn 0.2s ease;
}
@keyframes fadeIn {
from { opacity: 0; transform: translateY(5px); }
to { opacity: 1; transform: translateY(0); }
}
注意事项
- 翻译API通常有请求频率限制,需要做好错误处理和缓存机制
- 移动端需要额外处理touch事件
- 对于付费API需注意密钥安全性,前端直接暴露密钥存在风险
- 可考虑使用浏览器扩展的content script实现更稳定的划词功能



