Help us understand the problem. What is going on with this article?

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

More than 3 years have passed since last update.

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);
}
cockdoo
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした