LoginSignup
0

More than 5 years have passed since last update.

JavaScriptで欧文だけスタイルを変える

Last updated at Posted at 2017-09-17

cssで合成フォントを指定したはいいが、
欧文だけサイズを変えたい、ベースラインを調整したいと思ったときパッと出来そうになかったので
無理くりJavaScriptでタグ付け。そのメモ。

用途

  • 和文と欧文とでサイズやベースラインを変えて合成フォントを再現したいとき
  • かつhtmlの中身が静的じゃないとき
function addTagAndClassForEnglish(element) {
  let html = element.html();
  if (!html) { return }
  var newHtml = "";
  var beforeTextType;
  for(var i=0; i < html.length; i++){
    if(html.charCodeAt(i) >= 256) {
      if (beforeTextType === "en") {
        newHtml += '</span>' + html.slice(i, i + 1);
      } else {
      newHtml += html.slice(i, i + 1);
      }
      beforeTextType = "ja";
    } else {
      if (beforeTextType === "ja" || i === 0) {
        newHtml += '<span class="en">' + html.slice(i, i + 1);
      } else if (beforeTextType === "en" && i === html.length - 1) {
        newHtml += html.slice(i, i + 1) + '</span>';
      } else {
        newHtml += html.slice(i, i + 1);
      }
      beforeTextType = "en";
    }
  }
  element.empty().append(newHtml);
}

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
0