如何使用 javascript 在我的网站中添加带有自定义标志的语言翻译器?

How can I add language translator with custom flag in my website using javascript?

我正在使用 php 和 javascript。我想在我的网站中添加带有国旗的自定义语言选择器。我从 w3schools 教程中编写了以下代码;

<!DOCTYPE html>
<html lang="en-US">

<body>

    <h1>My Web Page</h1>

    <p>Hello everybody!</p>

    <p>Translate this page:</p>

    <div id="google_translate_element"></div>

    <script type="text/javascript">
        function googleTranslateElementInit() {
            new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element');
        }
    </script>

    <script type="text/javascript"
        src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>

    <p>You can translate the content of this page by selecting a language in the select box.</p>

</body>

</html>

在所有语言的状态下,我只对三种语言感兴趣(塔吉克语、俄语、英语)。我把这个语言标志是这样的;

<div class="flag">
      <a href="#" class="eng" data-lang="eng"><img class="img-fluid" src="./img/flag-eng.png" alt=""></a>
      <a href="#" class="taj" data-lang="es"><img class="img-fluid" src="./img/flag-taj.png" alt=""></a>
      <a href="#" class="rus" data-lang="rs"><img class="img-fluid" src="./img/flag-rus.png" alt=""></a>
</div>

但我不知道如何从 flag 更改所选语言。有帮助吗?

您可以在 Google 翻译功能中添加 includedLanguages: "en,es" 以仅启用特定语言。

示例

function googleTranslateElementInit() {
  new google.translate.TranslateElement({ pageLanguage: 'en',includedLanguages: "en,es" }, 'google_translate_element');
}

includedLanguages - 更新所需的语言。

HTML

<h1>My Web Page</h1>
<p>Hello everybody!</p>
<p>Translate this page:</p>
<div id="google_translate_element"></div>
<script type="text/javascript">
   function googleTranslateElementInit() {
       new google.translate.TranslateElement({ pageLanguage: 'en' }, 'google_translate_element');
   }
</script>
<script type="text/javascript"
   src="//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit"></script>
<p>You can translate the content of this page by selecting a language in the select box.</p>
<div class="flag">
   <a href="#" class="flag_link eng" data-lang="en">Eng<img class="img-fluid" src="./img/flag-eng.png" alt=""></a>
   <a href="#" class="flag_link taj" data-lang="es">ES<img class="img-fluid" src="./img/flag-taj.png" alt=""></a>
   <a href="#" class="flag_link rus" data-lang="ru">RS<img class="img-fluid" src="./img/flag-rus.png" alt=""></a>
</div>

CSS

#google_translate_element{
  display: none;
}

Javascript

var flags = document.getElementsByClassName('flag_link');


Array.prototype.forEach.call(flags, function(e){
  e.addEventListener('click', function(){
    var lang = e.getAttribute('data-lang'); 
    var languageSelect = document.querySelector("select.goog-te-combo");
    languageSelect.value = lang; 
    languageSelect.dispatchEvent(new Event("change"));
  }); 
});