0%

製作前端的簡繁轉換

 

內文

滑手機常常看到有些網站有簡繁轉換的效果 , 好奇是怎麼做的 , 研究一下發現應該? 是用 opencc-js 完成的 , 不然就要想別的後端方法太繁雜了 參考這篇
先引入 [opencc-js] (https://www.npmjs.com/package/opencc-js)
看一下官方範例自己加了一下前端畫面 , 主要就是把 panel 用 fixed 固定在右側 , 然後加入簡繁轉換按鈕 , 一次轉換帶有 html lang="zh-TW" 屬性轉換完以後會變成 html lang="cn"

html

1
2
3
4
<div id="panel">
<a id="btn-cn" href="javascript:;"></a>
<a id="btn-tw" href="javascript:;"></a>
</div>

css

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
      #panel{
position : fixed;
height:90px;
top:calc(50vh - 45px);
right:0;
background-color:#000;
opacity: 0.7;
border-radius: .25rem;
}

#panel a{
display:block;
color:#fff;
padding:10px;
position:relative;
}

#panel a:first-child::after {
content:'';
position:absolute;
bottom:0;
left:25%;
width:50%;
border-bottom: 1px solid #fff;
}

js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
document.getElementById('btn-cn').addEventListener('click', function () {
convLangCN();
});

document.getElementById('btn-tw').addEventListener('click', function () {
convLangTW();
});

function convLangTW() {
((async () => {
const convert = await OpenCC.Converter('cn', 'tw');

// 轉換整個頁面
const startNode = document.documentElement;

var lang = document.documentElement.lang;

// 將 zh-TW 標籤轉為 zh-CN 標籤
OpenCC.HTMLConverter(convert, startNode, lang , 'zh-TW').convert(); // 開始轉換
})());

}

function convLangCN() {
((async () => {
const convert = await OpenCC.Converter('tw', 'cn');

// 轉換整個頁面
const startNode = document.documentElement;

var lang = document.documentElement.lang;

// 將 zh-TW 標籤轉為 zh-CN 標籤
OpenCC.HTMLConverter(convert, startNode, lang , 'zh-CN').convert();

})());

}
關閉