Javascript 使用自定义标志图标实现 Google 翻译
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/10486833/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Implementing Google Translate with custom flag icons
提问by JasonH
Currently, I'm using the simple Google Translate drop-down menu found here: http://translate.google.com/translate_tools
目前,我正在使用此处提供的简单 Google 翻译下拉菜单:http: //translate.google.com/translate_tools
I'd like to also be able to click on some flag icons I have and trigger the same javascript calls that are called by the text-based links in the google translate widget.
我还希望能够点击我拥有的一些标志图标并触发由谷歌翻译小部件中基于文本的链接调用的相同 javascript 调用。
Anyone have ideas on how to accomplish this? I can't figure out how to make clicking on the flags initiate the same behavior as clicking on the google translate text links.
任何人都有关于如何实现这一目标的想法?我不知道如何让点击标志启动与点击谷歌翻译文本链接相同的行为。
回答by mogelbrod
Had a lot of fun finding a solution for this question!
找到这个问题的解决方案很有趣!
<!-- Use CSS to replace link text with flag icons -->
<ul class="translation-links">
<li><a href="#" class="spanish" data-lang="Spanish">Spanish</a></li>
<li><a href="#" class="german" data-lang="German">German</a></li>
</ul>
<!-- Code provided by Google -->
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false}, 'google_translate_element');
}
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>
<!-- Flag click handler -->
<script type="text/javascript">
$('.translation-links a').click(function() {
var lang = $(this).data('lang');
var $frame = $('.goog-te-menu-frame:first');
if (!$frame.size()) {
alert("Error: Could not find Google translate frame.");
return false;
}
$frame.contents().find('.goog-te-menu2-item span.text:contains('+lang+')').get(0).click();
return false;
});
</script>
回答by Boris Brdari?
@mogelbrod code isn't always working so I hacked it a bit.
@mogelbrod 代码并不总是有效,所以我对其进行了一些修改。
If user is logged in Google Account, Google will detect it's language and automatically translate language text so you won't be able to fire event on desired element because data-lang attribute won't be correct!
如果用户登录 Google 帐户,Google 将检测其语言并自动翻译语言文本,因此您将无法在所需元素上触发事件,因为 data-lang 属性将不正确!
Users that aren't logged in Google Account and American / English users will have this.
未登录 Google 帐户的用户和美国/英语用户将拥有此权限。
And for example; Croatian users will have this.
例如; 克罗地亚用户将拥有此功能。
In this case it's better to map language order. For example from above, that would be
在这种情况下,最好映射语言顺序。例如从上面,那将是
0 - English
1 - French
2 - German
3 - Italian
0 - 英语
1 - 法语
2 - 德语
3 - 意大利语
HTML:
HTML:
Note the data-placement property (you can change element order, but preserve placement as above).
请注意 data-placement 属性(您可以更改元素顺序,但保留上述位置)。
<div class="translation-icons" style="visibility:hidden">
<a href="#" class="eng" data-placement="0">eng icon</a>
<a href="#" class="fra" data-placement="1">fra icon</a>
<a href="#" class="ger" data-placement="2">ger icon</a>
<a href="#" class="ita" data-placement="3">ita icon</a>
</div>
JS: I had to change find selector. Note that when user choses language, there's no more "Choose Language" element in #google_translate_element div so I had to handle that, too.
JS:我不得不改变查找选择器。请注意,当用户选择语言时,#google_translate_element div 中不再有“选择语言”元素,因此我也必须处理它。
Also it's good not to show icons until all scripts (google translate) are loaded.
在加载所有脚本(谷歌翻译)之前不要显示图标也很好。
$(window).load(function () {
$('.translation-icons').css('visibility', 'visible');
$('.translation-icons a').click(function(e) {
e.preventDefault();
var placement = $(this).data('placement');
var lang_num = $('.translation-icons a').length;
var $frame = $('.goog-te-menu-frame:first');
if (!$frame.size()) {
alert("Error: Could not find Google translate frame.");
return false;
}
var langs = $('.goog-te-menu-frame:first').contents().find('a span.text');
if(langs.length != lang_num) placement = placement+1;
langs.eq(placement).click();
return false;
});
});
回答by joeyend
@mogelbrod, I used your code above and it worked perfectly on Chrome, tried it on Firefox and Safari, did not work. The span.click event doesn't fire the event handler of google translate.
@mogelbrod,我使用了你上面的代码,它在 Chrome 上运行良好,在 Firefox 和 Safari 上尝试过,但没有奏效。span.click 事件不会触发谷歌翻译的事件处理程序。
I came up with another method I just wanna share by using the google select instead the iframe-based plugin.
我想出了另一种方法,我只想通过使用 google select 而不是基于 iframe 的插件来分享。
<!-- Use CSS to replace link text with flag icons -->
<ul class="translation-links">
<li><a href="#" class="spanish" data-lang="Spanish">Spanish</a></li>
<li><a href="#" class="german" data-lang="German">German</a></li>
</ul>
<!-- Code provided by Google -->
<div id="google_translate_element"></div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', autoDisplay: false}, 'google_translate_element'); //remove the layout
}
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit" type="text/javascript"></script>
<script type="text/javascript">
function triggerHtmlEvent(element, eventName) {
var event;
if(document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, true);
element.dispatchEvent(event);
} else {
event = document.createEventObject();
event.eventType = eventName;
element.fireEvent('on' + event.eventType, event);
}
}
<!-- Flag click handler -->
$('.translation-links a').click(function(e) {
e.preventDefault();
var lang = $(this).data('lang');
$('#google_translate_element select option').each(function(){
if($(this).text().indexOf(lang) > -1) {
$(this).parent().val($(this).val());
var container = document.getElementById('google_translate_element');
var select = container.getElementsByTagName('select')[0];
triggerHtmlEvent(select, 'change');
}
});
});
</script>
Tested on: Chrome (win & Mac), Safari(Win & Mac), FireFox (win) and IE8
测试: Chrome (win & Mac), Safari (Win & Mac), FireFox (win) 和 IE8
By the way, the issue of the span.click event I encountered on Firefox and Safari could be solved by using the triggerHtmlEvent function above, I haven't tried it though.
顺便说一下,我在Firefox和Safari上遇到的span.click事件问题,可以通过上面的triggerHtmlEvent函数解决,不过我没试过。
回答by PalmWorks
Now no scripting is required!
现在不需要脚本了!
Add the tag #googtrans(TO_LANG_CODE)
to the address that your respective flag links to.
将标签添加#googtrans(TO_LANG_CODE)
到您各自的标志链接到的地址。
Here TO_LANG_CODE
is the language code for the language you want.
This assumes the page uses Google Website Translator as in the question and your original language can be automatically identified.
这TO_LANG_CODE
是您想要的语言的语言代码。这假设该页面使用问题中的 Google 网站翻译器,并且可以自动识别您的原始语言。
Identifying the original language can help avoid errors, to do so use the form #googtrans(FROM_LANG_CODE|TO_LANG_CODE)
.
识别原始语言有助于避免错误,为此请使用表格#googtrans(FROM_LANG_CODE|TO_LANG_CODE)
。
Example:
http://nykopingsguiden.se/#googtrans(se|es)translates the Swedish page
http://nykopingsguiden.sefrom Swedish to Spanish.
示例:
http: //nykopingsguiden.se/#googtrans(se|es)将瑞典语页面
http://nykopingsguiden.se从瑞典语翻译成西班牙语。
回答by Kamal Pratap
Implementing Google Translate With Custom Flag Icons
使用自定义标志图标实现 Google 翻译
Refer This Link
参考这个链接
http://www.freshcodehub.com/Article/26/implementing-google-translate-with-custom-flag-icons
http://www.freshcodehub.com/Article/26/implementing-google-translate-with-custom-flag-icons
The benifit of this custom list is than we can hide the google translator widget and use all the language to translate the web page.
这个自定义列表的好处是我们可以隐藏谷歌翻译小部件并使用所有语言来翻译网页。
<div id="google_translate_element" style="display: none">
</div>
<script type="text/javascript">
function googleTranslateElementInit() {
new google.translate.TranslateElement({ pageLanguage: 'en', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false }, 'google_translate_element');
}
</script>
<script src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"
type="text/javascript"></script>
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
function translate(lang) {
var $frame = $('.goog-te-menu-frame:first');
if (!$frame.size()) {
alert("Error: Could not find Google translate frame.");
return false;
}
$frame.contents().find('.goog-te-menu2-item span.text:contains(' + lang + ')').get(0).click();
return false;
}
</script>
回答by Jind?ich Prokop
This is a fix to Boris Samard?ija's solution as it fails whenever the names of the languages in the visitor's language result in their different order.
这是对 Boris Samard?ija 解决方案的修复,因为只要访问者语言中的语言名称导致不同的顺序,它就会失败。
First, have correct language codes in some attribute of the icons. E.g.
<a href="#" data-lang="German" data-class="de">
.
Then, make sure you will have google translate element available, e.g.:
首先,在图标的某些属性中有正确的语言代码。例如
<a href="#" data-lang="German" data-class="de">
。然后,确保您有可用的谷歌翻译元素,例如:
<script type="text/javascript">
var tis;
function googleTranslateElementInit() {
tis = new google.translate.TranslateElement({defaultLanguage: 'en', pageLanguage: 'en', includedLanguages: 'en,es,it,de,fr', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false}, 'google_translate_element');
}
</script>
This allows you to find the language name to be translated to in the language of the visitor through the property sl
of property C
of the google element, which is a mapping of language codes to the names:
这允许您通过google 元素的 propertysl
属性找到要翻译成访问者语言的语言名称,该属性C
是语言代码到名称的映射:
$(window).load(function () {
$('.translation-links a').click(function(e) {
e.preventDefault();
var $frame = $('.goog-te-menu-frame:first');
if (!$frame.size()) {
alert("Error: Could not find Google translate frame.");
return false;
}
var codes_names = tis.C.sl;
var selected_lang = codes_names[$(this).data('class')];
$('.goog-te-menu-frame:first').contents().find('a span.text:contains(' + selected_lang + ')').click();
return false;
});
});
回答by Aleksandra Chuprova
I was struggling with this problem too - to make the flags clickable and to hide the gtranslate select menu instead. Google probably changes thing from time to time so the codes above didn't work for me... Thought they brought me to the good ideas and finally the solution.
我也在努力解决这个问题 - 使标志可点击并隐藏 gtranslate 选择菜单。谷歌可能会不时改变事情,所以上面的代码对我不起作用......以为他们给我带来了好主意,最后是解决方案。
map the languages. Choose the languages you need and loog good in which order they are shown in the gtranslate dropdow - the flag links should have the same order. It is important!
in the function proveded bu google function googleTranslateElementInit(), add the MultilanguagePage: true parametr. I have also commented out the default language and pagelanguage... for some reason this works...
//load the script of google <script src="http://translate.google.com/translate_a/element.js? cb=googleTranslateElementInit" type="text/javascript"></script> <script> function googleTranslateElementInit() { new google.translate.TranslateElement({ //defaultLanguage: 'en', //pageLanguage: 'en', includedLanguages: 'de,nl,en,es,it,fr', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false, multilanguagePage: true}, 'google_translate_element') }; //this one I need because of the first menu with "select the language" item, after the first click on the language it disappears var clickCount = 0; $(window).load(function () { $('.translation-icons a').click(function(e) { e.preventDefault(); var $frame = $('.goog-te-menu-frame:first'); if (!$frame.size()) { alert("Error: Could not find Google translate frame."); return false; } //find the a links element inside the gtranlate first frame var langs = $('.goog-te-menu-frame:first').contents().find('.goog-te-menu2 a'); //the number of the language in flag-elements var placement = $(this).data('placement'); //this again I need to adjust the mapping numbers of the languages in the flag elements if (clickCount == 0){ placement = $(this).data('placement')+1; clickCount++; } //and finaly imitate click on the gtranslate element which is the same as the number of the language in flag link langs.eq(placement).find('span.text').click(); return false; }); });
映射语言。选择您需要的语言并查看它们在 gtranslate 下拉菜单中的显示顺序 - 标志链接应具有相同的顺序。这很重要!
在 google 函数 googleTranslateElementInit() 验证的函数中,添加 MultilanguagePage: true 参数。我还注释掉了默认语言和页面语言......出于某种原因,这有效......
//load the script of google <script src="http://translate.google.com/translate_a/element.js? cb=googleTranslateElementInit" type="text/javascript"></script> <script> function googleTranslateElementInit() { new google.translate.TranslateElement({ //defaultLanguage: 'en', //pageLanguage: 'en', includedLanguages: 'de,nl,en,es,it,fr', layout: google.translate.TranslateElement.InlineLayout.SIMPLE, autoDisplay: false, multilanguagePage: true}, 'google_translate_element') }; //this one I need because of the first menu with "select the language" item, after the first click on the language it disappears var clickCount = 0; $(window).load(function () { $('.translation-icons a').click(function(e) { e.preventDefault(); var $frame = $('.goog-te-menu-frame:first'); if (!$frame.size()) { alert("Error: Could not find Google translate frame."); return false; } //find the a links element inside the gtranlate first frame var langs = $('.goog-te-menu-frame:first').contents().find('.goog-te-menu2 a'); //the number of the language in flag-elements var placement = $(this).data('placement'); //this again I need to adjust the mapping numbers of the languages in the flag elements if (clickCount == 0){ placement = $(this).data('placement')+1; clickCount++; } //and finaly imitate click on the gtranslate element which is the same as the number of the language in flag link langs.eq(placement).find('span.text').click(); return false; }); });
And finaly the html of the "flag elements".(for now it's only text inside the , but you can put any img there if you want) And don;t forget to create the google translate element!
最后是“标志元素”的 html。(现在它只是 里面的文本,但如果你愿意,你可以把任何 img 放在那里)并且不要忘记创建谷歌翻译元素!
<!-- Code provided by Google -->
<div id="google_translate_element"></div>
<div class="translation-icons">
<a href="#" class="nl" data-placement="0">nl</a>
<a href="#" class="de" data-placement="1">de</a>
<a href="#" class="en" data-placement="2">en</a>
<a href="#" class="fr" data-placement="3">fr</a>
<a href="#" class="it" data-placement="4">it</a>
<a href="#" class="sp" data-placement="5">es</a>
</div>
回答by Isaac
default language issue sorted with the following code
使用以下代码排序的默认语言问题
if(lang!="English"){
$frame.contents().find('.goog-te-menu2-item span.text:contains('+lang+')').get(0).click();
}else{
console.log($frame2.contents().find('.goog-te-banner .goog-te-button button').get(0));
$frame2.contents().find('.goog-te-banner .goog-te-button button').get(1).click();
}
回答by Riki_VaL
To implement a totally backend solution (before the translate.jsincluded) you just can create a php file which contains
要实现完全后端解决方案(在包含translate.js之前),您只需创建一个 php 文件,其中包含
<?php setcookie('googtrans', '/en'); header('location:index.html')?>
If you want your page in spanish you just add other php file like:
如果您希望您的页面为西班牙语,您只需添加其他 php 文件,例如:
<?php setcookie('googtrans', '/en/es'); header('location:index.html')?>
Finally link this file to any 'a' tag
最后将此文件链接到任何“a”标签
<a href="defaultLang.php"></a>
回答by Lu Blue
I think this jsfiddle will help you out: https://jsfiddle.net/solodev/0stLrpqg/
我认为这个 jsfiddle 会帮助你:https://jsfiddle.net/solodev/0stLrpqg/
function googleTranslateElementInit() {
new google.translate.TranslateElement({pageLanguage: 'en', layout: google.translate.TranslateElement.FloatPosition.TOP_LEFT}, 'google_translate_element');
}
function triggerHtmlEvent(element, eventName) {
var event;
if (document.createEvent) {
event = document.createEvent('HTMLEvents');
event.initEvent(eventName, true, true);
element.dispatchEvent(event);
} else {
event = document.createEventObject();
event.eventType = eventName;
element.fireEvent('on' + event.eventType, event);
}
}
jQuery('.lang-select').click(function() {
var theLang = jQuery(this).attr('data-lang');
jQuery('.goog-te-combo').val(theLang);
//alert(jQuery(this).attr('href'));
window.location = jQuery(this).attr('href');
location.reload();
});