如何在HTML页面实现类似谷歌翻译下拉框的Microsoft Azure Translator功能?
实现基于Azure Translator的页面翻译下拉框功能
一、核心实现思路
借助Azure Translator API的文本翻译能力,结合HTML下拉控件、JavaScript请求处理,还原类似谷歌翻译的交互体验:
- 提供源语言与目标语言的下拉选择器,支持语言互换
- 点击翻译按钮后批量翻译页面指定区域的文本内容
- 适配页面悬浮控件样式,保证操作便捷性
二、完整代码实现
1. HTML结构
<!DOCTYPE html> <html lang="zh-CN"> <head> <meta charset="UTF-8"> <title>Azure翻译演示</title> <link rel="stylesheet" href="styles.css"> </head> <body> <!-- 翻译悬浮控件 --> <div class="translator-widget"> <select id="sourceLang"> <option value="zh-Hans">中文(简体)</option> <option value="en">英语</option> <option value="ja">日语</option> <!-- 可扩展更多Azure支持的语言代码 --> </select> <span class="swap-btn">↔</span> <select id="targetLang"> <option value="en">英语</option> <option value="zh-Hans">中文(简体)</option> <option value="ja">日语</option> </select> <button id="translateBtn">翻译</button> </div> <!-- 需要翻译的页面内容区域 --> <div class="content-to-translate"> <h1>欢迎使用Azure翻译工具</h1> <p>这是一段需要被翻译的示例文本,你可以替换成任意页面内容。</p> <p>更多段落示例,用于测试多文本翻译效果。</p> </div> <script src="script.js"></script> </body> </html>
2. CSS样式(styles.css)
/* 翻译控件样式,模拟谷歌翻译悬浮效果 */ .translator-widget { position: fixed; top: 20px; right: 20px; display: flex; gap: 8px; padding: 10px; background: #fff; border: 1px solid #ddd; border-radius: 24px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); z-index: 9999; } .translator-widget select { padding: 6px 12px; border: 1px solid #ddd; border-radius: 16px; font-size: 14px; cursor: pointer; } .swap-btn { font-size: 18px; cursor: pointer; align-self: center; color: #666; } #translateBtn { padding: 6px 16px; background: #0078d4; color: #fff; border: none; border-radius: 16px; cursor: pointer; font-size: 14px; } #translateBtn:hover { background: #005a9e; } .content-to-translate { max-width: 800px; margin: 50px auto; padding: 0 20px; }
3. JavaScript逻辑(script.js)
// 替换为你的Azure Translator API密钥和区域 const AZURE_KEY = "你的Azure API密钥"; const AZURE_REGION = "你的API区域(如eastasia)"; const TRANSLATE_ENDPOINT = "https://api.cognitive.microsofttranslator.com/translate"; // 获取DOM元素 const sourceLangSelect = document.getElementById('sourceLang'); const targetLangSelect = document.getElementById('targetLang'); const translateBtn = document.getElementById('translateBtn'); const contentArea = document.querySelector('.content-to-translate'); // 语言互换功能 document.querySelector('.swap-btn').addEventListener('click', () => { const temp = sourceLangSelect.value; sourceLangSelect.value = targetLangSelect.value; targetLangSelect.value = temp; }); // 翻译按钮点击事件 translateBtn.addEventListener('click', async () => { const sourceLang = sourceLangSelect.value; const targetLang = targetLangSelect.value; if (sourceLang === targetLang) { alert('源语言与目标语言不能相同'); return; } // 提取页面中需要翻译的文本节点 const textNodes = []; const walk = document.createTreeWalker(contentArea, NodeFilter.SHOW_TEXT, null, false); let node; while (node = walk.nextNode()) { const text = node.textContent.trim(); if (text) { textNodes.push({ node, text }); } } if (textNodes.length === 0) return; // 调用Azure翻译API try { const response = await fetch(`${TRANSLATE_ENDPOINT}?api-version=3.0&from=${sourceLang}&to=${targetLang}`, { method: 'POST', headers: { 'Ocp-Apim-Subscription-Key': AZURE_KEY, 'Ocp-Apim-Subscription-Region': AZURE_REGION, 'Content-Type': 'application/json' }, body: JSON.stringify(textNodes.map(item => ({ Text: item.text }))) }); if (!response.ok) throw new Error(`API请求失败: ${response.status}`); const results = await response.json(); // 将翻译结果替换回页面 textNodes.forEach((item, index) => { item.node.textContent = results[index].translations[0].text; }); } catch (error) { console.error('翻译出错:', error); alert('翻译失败,请检查API密钥和网络连接'); } });
三、关键说明
- Azure API配置: 必须替换代码中的
AZURE_KEY和AZURE_REGION为你自己的密钥和区域信息 - 语言代码: 所有语言代码需遵循Azure Translator支持的标准代码(如
zh-Hans代表简体中文,en代表英语) - 文本提取: 使用
TreeWalker遍历页面文本节点,确保只翻译可见内容,避免翻译脚本或样式代码 - 性能优化: 批量提交文本到API,减少请求次数,提升翻译效率
内容的提问来源于stack exchange,提问作者Sunil Mathari
相关产品推荐
相关产品推荐

