如何在前端中加入免费google网页翻译功能
| Visit:420
添加如下 js 脚本, 保存成 .js 文件,然后在页面中 </body> 结束前调用。
功能:在页面右下角添加一个下拉选框,点击切换, 可以通过谷歌翻译自动生成多种语言的翻译结果。
// 创建<style>标签并设置CSS样式
var style = document.createElement('style');
style.innerHTML = `
#translator-container {
position: fixed;
bottom: 20px;
right: 20px;
z-index: 1000;
}
`;
document.body.appendChild(style);
// 创建<div>元素并添加下拉选框
var translatorContainer = document.createElement('div');
translatorContainer.id = 'translator-container';
translatorContainer.innerHTML = `
<select id="language-select">
<option value="en">English</option>
<option value="es">Spanish</option>
<option value="fr">French</option>
<option value="de">German</option>
<option value="it">Italian</option>
<option value="ja">Japanese</option>
<option value="zh-CN">Chinese (Simplified)</option>
<option value="ru">Russian</option>
<option value="ar">Arabic</option>
<option value="pt">Portuguese</option>
<option value="ko">Korean</option>
<option value="nl">Dutch</option>
<option value="sv">Swedish</option>
<option value="tr">Turkish</option>
<option value="pl">Polish</option>
<option value="vi">Vietnamese</option>
<option value="el">Greek</option>
<option value="th">Thai</option>
</select>
`;
document.body.appendChild(translatorContainer);
// JavaScript代码
document.getElementById('language-select').addEventListener('change', function() {
const selectedLanguage = this.value;
const currentUrl = window.location.href;
if (document.domain.includes('translate.goog')) {
const separator = currentUrl.includes('?') ? '&' : '?';
const modifiedUrl = currentUrl.replace(/_x_tr_tl=[^&]*/, `_x_tr_tl=${selectedLanguage}`);
window.open(modifiedUrl, '_blank');
} else {
if (currentUrl.includes('https://translate.google.com/translate')) {
const url = new URL(currentUrl);
url.searchParams.set('tl', selectedLanguage);
window.open(url.href, '_blank');
} else {
const translateBaseUrl = 'https://translate.google.com/translate?hl=en&sl=auto&u=';
const translatedUrl = `${translateBaseUrl}${encodeURIComponent(currentUrl)}&tl=${selectedLanguage}`;
window.open(translatedUrl, '_blank');
}
}
});
如果要在 wordpress 主题中调用, 则将js 文件保存到 主题文件的 js 目录中,并在主题的 function.php 中添加以下代码:
function add_custom_script_to_footer() { wp_enqueue_script( 'googletranslate', get_template_directory_uri() . '/js/googletranslate.js', array(), '1.0', true ); } add_action( 'wp_enqueue_scripts', 'add_custom_script_to_footer' );