脚本加载后如何强制Google翻译翻译页面?

问题描述:

<script type="text/javascript"> 

function googleTranslateElementInit() { 
  new google.translate.TranslateElement(
  {
      pageLanguage: 'ru',
      layout: google.translate.TranslateElement.FloatPosition.TOP_LEFT,
      autoDisplay: true
  },
  'google_translate_element'
  ); 
}

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

脚本已加载,但加载后不会翻译页面.我需要从选择框中选择语言.如何在不从选择框中选择语言的情况下使其自动翻译?

The scripts loads, but after it loads it doesn't translate the page. I need to select the language from the selectbox. How to make it auto translate without selecting the language from the select box?

您需要添加Google翻译的Cookie的基本思想是在加载元素时寻找它,然后您甚至可以使用CSS隐藏Google翻译元素.

The basic idea that you need to add cookies that google translate looks for when it's loading the element, and then you can even hide google translate elements using CSS.

这是使用 js.cookie 的简短示例:

    <div class="custom-translate" st yle="display: none;" id="google_translate_element"></div>


<!-- ASYNCHRONOUS Google Translate -->
<script type="text/javascript">
    function googleTranslateElementInit() {
        new google.translate.TranslateElement({
            pageLanguage: 'en',
            layout: google.translate.TranslateElement.FloatPosition.TOP_RIGHT,
            autoDisplay: false
        }, 'google_translate_element');
    }

    (function () {
        var googleTranslateScript = document.createElement('script');
        googleTranslateScript.type = 'text/javascript';
        googleTranslateScript.async = true;
        googleTranslateScript.src =
            '//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit';
        (document.getElementsByTagName('head')[0] || document.getElementsByTagName('body')[0]).appendChild(
            googleTranslateScript);
    })();

    Cookies.set('GoogleAccountsLocale_session', 'iw', { expires: 999});
    Cookies.set('googtrans', '/en/iw', { expires: 999});
</script>

CSS隐藏Google翻译元素:

CSS to hide the google translate elements:

<style>
.goog-te-banner-frame,.custom-translate {
        display: none;
}

body {
        top: 0 !important;
    }
.goog-tooltip {
    display: none !important;
}
.goog-tooltip:hover {
    display: none !important;
}
.goog-text-highlight {
    background-color: transparent !important;
    border: none !important; 
    box-shadow: none !important;
}

</style>