监视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>本文内容仅供个人学习/研究/参考使用,不构成任何决策建议或专业指导。分享/转载时请标明原文来源,同时请勿将内容用于商业售卖、虚假宣传等非学习用途哦~感谢您的理解与支持!