网页添加非中国大陆IP访问显示Google网页翻译按钮

在网站的head或footer上添加如下代码(我用discuz,那就是在header_common.php最后的位置添加PC左侧贴边版):

    <script>
    fetch("https://ipapi.co/json/") // 你也可以换成 ipinfo.io、ip.sb
      .then(response => response.json())
      .then(data => {
        if (data.country_code !== "CN") {
          // 如果不是中国用户,则加载 Google 翻译
          var gtDiv = document.createElement("div");
          gtDiv.id = "google_translate_element";
          gtDiv.style = `
            position: fixed;
            top: 20%;
            left: 0;
            transform: translateY(0);
            z-index: 9999;
            background-color: white;
            padding: 6px;
            border-radius: 0 6px 6px 0;
            box-shadow: 0 2px 6px rgba(0,0,0,0.2);
          `;
          document.body.appendChild(gtDiv);

          // 创建初始化函数
          window.googleTranslateElementInit = function() {
            new google.translate.TranslateElement({
              pageLanguage: 'zh-CN',
              includedLanguages: 'en,zh-CN,ja,ko,fr,de,es,ru',
              layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
              multilanguagePage: true
            }, 'google_translate_element');
          };
    
          // 加载 Google Translate 脚本
          var script = document.createElement("script");
          script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
          document.body.appendChild(script);
        }
      })
      .catch(error => {
        console.warn("IP 查询失败,默认不加载 Google 翻译:", error);
      });
    </script>

移动顶部居中版:

<script>
// 使用 ipapi.co 判断国家是否为 CN(中国)
fetch("https://ipapi.co/json/")
  .then(response => response.json())
  .then(data => {
    if (data.country_code !== "CN") {
      // 显示翻译容器
      document.getElementById("google_translate_element").style.display = "block";

      // 加载 Google 翻译脚本
      var script = document.createElement("script");
      script.type = "text/javascript";
      script.src = "//translate.google.com/translate_a/element.js?cb=googleTranslateElementInit";
      document.body.appendChild(script);
    }
  })
  .catch(err => {
    console.warn("IP 地理位置判断失败,默认不加载翻译控件。", err);
  });

// 初始化函数,只有加载 script 后才会调用
function googleTranslateElementInit() {
  new google.translate.TranslateElement({
    pageLanguage: 'zh-CN',
    includedLanguages: 'en,zh-CN,ja,ko,fr,de,es,ru',
    layout: google.translate.TranslateElement.InlineLayout.SIMPLE,
    multilanguagePage: true
  }, 'google_translate_element');
}
</script>
<!--Google翻译代码仅非中国大陆IP显示↑-->

 

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注