Qiita Teams that are logged in
You are not logged in to any team

Log in to Qiita Team
Community
OrganizationEventAdvent CalendarQiitadon (β)
Service
Qiita JobsQiita ZineQiita Blog
0
Help us understand the problem. What are the problem?

More than 3 years have passed since last update.

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

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);
}
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
0
Help us understand the problem. What are the problem?