Js实现划词翻译
划词翻译的实现思路
划词翻译功能可以通过监听用户鼠标选中文本的事件,获取选中的文本内容,然后调用翻译API进行翻译,最后将翻译结果显示在页面上。
获取选中文本
通过window.getSelection()方法可以获取用户选中的文本内容。监听mouseup事件可以捕获用户完成选中的时刻。
document.addEventListener('mouseup', function() {
const selection = window.getSelection();
const selectedText = selection.toString().trim();
if (selectedText.length > 0) {
// 有选中文本
}
});
调用翻译API
可以使用免费的翻译API如Google Translate API或百度翻译API。以下示例使用百度翻译API(需要先申请API key):
function translateText(text, callback) {
const appid = '你的APPID';
const 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 => {
if (data.trans_result) {
callback(data.trans_result[0].dst);
}
});
}
显示翻译结果
创建一个浮动div来显示翻译结果,可以跟随鼠标位置:
function showTranslation(text, x, y) {
let popup = document.getElementById('translation-popup');
if (!popup) {
popup = document.createElement('div');
popup.id = 'translation-popup';
popup.style.position = 'absolute';
popup.style.zIndex = '9999';
popup.style.backgroundColor = '#fff';
popup.style.border = '1px solid #ccc';
popup.style.padding = '8px';
popup.style.borderRadius = '4px';
popup.style.boxShadow = '0 2px 10px rgba(0,0,0,0.1)';
document.body.appendChild(popup);
}
popup.style.left = `${x}px`;
popup.style.top = `${y + 20}px`;
popup.textContent = text;
}
完整实现
将以上代码整合,实现完整的划词翻译功能:
document.addEventListener('mouseup', function(e) {
const selection = window.getSelection();
const selectedText = selection.toString().trim();
if (selectedText.length > 0) {
translateText(selectedText, function(translation) {
showTranslation(translation, e.clientX, e.clientY);
});
}
});
function translateText(text, callback) {
// 实现翻译API调用
}
function showTranslation(text, x, y) {
// 实现显示翻译结果
}
样式优化
为翻译弹窗添加CSS样式,使其更美观:
#translation-popup {
max-width: 300px;
font-size: 14px;
line-height: 1.5;
color: #333;
pointer-events: none;
transition: opacity 0.2s;
}
注意事项
- 翻译API通常有调用频率限制,需要合理控制调用次数
- 跨域问题可能需要通过后端代理解决
- 移动端适配需要考虑触摸事件
- 长时间显示的弹窗可以添加关闭按钮
这种方法可以实现基本的划词翻译功能,如需更复杂的功能可以在此基础上扩展。







