监视DOM树属性的更改

最近客户反映页面会有乱码的情况,查看后发现只有英文大写字母乱了

 谷歌浏览器有翻译功能,在翻译成中文后会出现这种情况。

<html id="html" lang="zh-CN">
之前lang=“en”,如果浏览器设置了总是询问,在检测到是en后会提示是否翻译。
发现在翻译后,html的lang会变化,然后就想到监测lang的属性变化,在翻译后在给它改回来。

但是在翻译后修改,lang属性值确实是修改回来了,但是码还是乱的,只能退而求其次在翻译后提示用户

<!DOCTYPE html>
<html id="html" lang="zh-CN">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width,initial-scale=1.0">
    <link href="<%= BASE_URL %>static/style.css" rel="stylesheet">
  </head>
  <body>
    <noscript>
      <strong>We're sorry but statement doesn't work properly without JavaScript enabled. Please enable it to continue.</strong>
    </noscript>
    <div id="app"></div>
    <!-- built files will be auto injected -->
  </body>
  <script type="text/javascript">
    var MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver;
    var element = document.querySelector('#html');
    var observer = new MutationObserver(function(mutations) {
      mutations.forEach(function(mutation) {
        if (mutation.attributeName === "lang" && mutation.target.className) {
          element.removeAttribute('lang');
          element.removeAttribute('class');
          this.$uniteMsg('翻译可能会导致部分文字乱码',"warning",0);
        }
      });
    });

    observer.observe(element, {
      attributes: true,  //configure it to listen to attribute changes,
      attributeFilter: ['lang']
    });
  </script>
</html>

MutationObserver()创建并返回一个新的 MutationObserver 它会在指定的DOM发生变化时被调用。

observe()配置MutationObserver在DOM更改匹配给定选项时,通过其回调函数开始接收通知

原文地址:https://www.cnblogs.com/gxp69/p/12759869.html