console
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title class="lang" key="title"></title>
</head>
<body style="padding: 50px">
<h2 class="lang" key="hello"></h2>
<p class="lang" key="name"></p>
<div>
<button class="lang" key="switch1" onclick=document.children[0].setAttribute('lang','en')></button>
<button class="lang" key="switch2" onclick=document.children[0].setAttribute('lang','zh-CN')></button>
</div>
</body>
<script>
let langPackage = {
'en': {
hello: 'Hello',
name: 'Nowell',
title: 'title',
switch1: 'english',
switch2: 'chinese'
},
'zh-CN': {
hello: '你好',
name: '小杨',
title: '标题',
switch1: '英文',
switch2: '中文'
}
}
let changeLang = () => {
let lang = document.children[0].lang || 'en'
Array.from(document.getElementsByClassName('lang')).forEach((el, index) => {
let key = el.getAttribute('key')
el.innerText = langPackage[lang][key]
})
}
let mutationObserver = new MutationObserver((mutationList, observer) => changeLang())
mutationObserver.observe(document.children[0], { attributes: true })
window.addEventListener('DOMContentLoaded', changeLang)
</script>
</html>