当前位置:首页 > JavaScript

Js实现划词翻译

2026-03-01 19:18:11JavaScript

划词翻译的实现思路

划词翻译功能可以通过监听用户鼠标选中文本的事件,获取选中的文本内容,然后调用翻译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;
}

注意事项

  1. 翻译API通常有调用频率限制,需要合理控制调用次数
  2. 跨域问题可能需要通过后端代理解决
  3. 移动端适配需要考虑触摸事件
  4. 长时间显示的弹窗可以添加关闭按钮

这种方法可以实现基本的划词翻译功能,如需更复杂的功能可以在此基础上扩展。

Js实现划词翻译

标签: Js
分享给朋友:

相关文章

Js实现reset

Js实现reset

使用 HTMLFormElement.reset() 方法 通过 JavaScript 直接调用表单的 reset() 方法可以重置表单内的所有输入字段为初始值: document.getElem…

Js实现utext

Js实现utext

JavaScript 实现 UText(用户文本处理) 在 JavaScript 中实现 UText(User Text)处理通常涉及文本操作、格式化或自定义功能。以下是几种常见的实现方法: 字符…

Js轮训实现

Js轮训实现

轮询的实现方法 轮询(Polling)是一种客户端定期向服务器发送请求以获取最新数据的技术。适用于实时性要求不高的场景,实现简单但可能增加服务器负载。 使用setInterval实现基础轮询 通过s…

Js实现 toggle

Js实现 toggle

使用 classList.toggle 方法 通过 classList.toggle 可以轻松切换元素的类名。该方法接受一个类名作为参数,如果元素已存在该类名则移除,不存在则添加。 const bu…

Js实现decimal

Js实现decimal

实现 Decimal 类型的方法 在 JavaScript 中,原生不支持精确的 Decimal 类型,但可以通过以下方法实现高精度小数运算。 使用第三方库 推荐使用成熟的第三方库来处理 Decim…

Js实现wordclock

Js实现wordclock

实现 Word Clock 的基本思路 Word Clock 是一种以文字显示时间的时钟,例如 "IT IS HALF PAST TEN"。实现这种时钟需要将时间转换为对应的单词组合。 时间转换为单…