LoginSignup
4
2

More than 3 years have passed since last update.

JavaScriptでサイトの言語切り替え2

Last updated at Posted at 2020-03-10

昔作った物の書き換えた物です

JavaScriptでサイトの言語切り替え

class Lang {
  lang;
  el;
  data;
  ctx;
  content;
  afterContent;
  address;
  constructor(obj) {
    this.el = obj.el || "body";
    this.data = obj.data || {};
    this.lang = obj.data.def || "en";
    this.address = obj.data.address || false;
    this.ctx = document.querySelector(this.el);
    this.content = this.ctx.textContent;
    this.afterContent = this.ctx.textContent;
    this.loads();
    return this;
  }
  run() {
    for (const key in this.data) {
      let val = this.data[key];
      const reg = new RegExp(`\%\{${key}\}`, "g");
      this.afterContent = this.afterContent.replace(reg, val[this.lang]);
    }
    this.ctx.textContent = this.afterContent;
  }
  loads() {
    if(location.hash) {
      this.lang = location.hash.split("#")[1];
    } else {
      this.lang = ((window.navigator.languages
        && window.navigator.languages[0])
        || window.navigator.language
        || window.navigator.userLanguage
        || window.navigator.browserLanguage).split("-")[0];
    }
    this.run();
    if(this.adress) history.replaceState("", "", `#${this.lang}`);
  }
}

使用方法

element はcssセレクター指定
(未指定body)

def は初期表示の言語
(未指定時en or 先に宣言したlangに合わせる)

adress は URLの後ろにセクターを付けるか
(未指定時false 指定時true)
trueのとき ○○.com/home#ja
#ja の部分を変えるとその言語になる

<div id="title">
  %{title} %{message}
  <div id="test">
    %{title}
  </div>
</div>

<div id="box">
  %{box}
</div>

<!-- 上記のコードを読み込む -->

<script>
new Lang({
  el: "#title", // element
  def: "ja", // default
  address: false, // adressbar
  data: {
    "title": {
      "ja": "タイトル",
      "en": "title"
    },
    "message": {
      "ja": "メッセージ",
      "en": "message"
    }
  }
});

new Lang({
  data: {
    "box": {
      "ja": "ボックス",
      "en": "box"
    }
  }
});
</script>
4
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
4
2