Written by Toshiki

Webサイトにフォントサイズ変更ボタンを実装する方法(jQuery使用)

JavaScript Web制作

こんにちは、トシキです。
今回はフォントサイズ変更機能の実装について解説していきます。

「閲覧するユーザーの操作によってサイズ変更を可能にしたい」
「ページの一部だけサイズ変更したい」

このような悩みにお答えします。
サイトリニューアル案件で遭遇したので、実装方法をまとめることにしました。

本記事の内容

スポンサードサーチ

【1】Webサイトにフォントサイズ変更ボタンを実装する方法

Webサイトにフォントサイズ変更ボタンを実装する方法

こちらがフォントサイズ変更機能を実装したデモサイトになります。

1-1. HTML

  
    <div class="ly_siteWrapper">
      <header class="ly_header">
        <div class="ly_header_inner">
          <nav class="bl_headerNav" aria-label="サイト内メニュー">
            <ul class="bl_headerList">
              <li>
                <a href="#">TOPページ</a>
              </li>
              <li>
                <a href="#">下層ページ1</a>
              </li>
              <li>
                <a href="#">下層ページ2</a>
              </li>
            </ul>
          </nav>
          <div class="bl_sizeBtn_wrap">
            <span>文字サイズ変更</span>
            <button type="button" class="bl_sizeBtn" id="fz_sm">小</button>
            <button type="button" class="bl_sizeBtn is_active" id="fz_md">中</button>
            <button type="button" class="bl_sizeBtn" id="fz_lg">大</button>
          </div>
        </div>
      </header>
      <main class="ly_main">
        <section class="ly_section">
          <div class="ly_section_inner">
            <h2 class="el_lv2Heading">TOPページです。</h2>
            <ul class="bl_sampleList">
              <li>ここのフォントサイズは<span>rem</span>指定です(1rem)。</li>
              <li class="bl_fzPx">ここのフォントサイズは<span>px</span>指定です(16px)。</li>
            </ul>
          </div>
        </section>
      </main>
    </div>
  

大中小の変更ボタンは<button>タグを使用し、それぞれにidを付与しています。

1-2. CSS

  
    html {
      font-size: 100%;/* ここをjQueryで書き換えます */
      /* ↑解説のために指定していますが、デフォルトは100%なので通常は指定不要です */
    }
    
    body {
      color: #2C2C2C;
      font-family: "Helvetica Neue", "Helvetica", "Hiragino Sans", "Hiragino Kaku Gothic ProN", "Arial", "Yu Gothic", "Meiryo", sans-serif;
      font-size: 1rem;/* remで指定(1rem = 16px) */
      line-height: 1;
    }

    a {
      transition: color 0.4s;
    }
    
    .ly_siteWrapper {
      display: flex;
      flex-direction: column;
      min-height: 100vh;
    }
    
    .ly_header {
      padding: 15px 56px;
    }
    
    .ly_header_inner {
      display: flex;
      align-items: center;
      justify-content: space-between;
      width: min(100%, 880px);
      margin: 0 auto;
    }
    
    .ly_main {
      background-color: #fafafa;
      flex: 1;
      overflow-x: hidden;
    }
    
    .ly_section {
      padding: 90px 0;
    }
    
    .ly_section_inner {
      padding: 0 15px;
      text-align: center;
      width: min(100%, 880px);
      margin: 0 auto;
    }
    
    .bl_headerList {
      display: flex;
      align-items: center;
      justify-content: space-between;
    }
    
    .bl_headerList > * + * {
      margin-left: 56px;
    }
    
    .bl_headerList a {
      line-height: 1.5;
      padding: 10px;
    }
    
    /********************/
    /* ボタンのスタイル */
    /********************/
    .bl_sizeBtn_wrap {
      display: inline-flex;
      align-items: flex-end;
      font-weight: 500;
    }
    
    .bl_sizeBtn_wrap > span {
      font-size: 14px;
      letter-spacing: 0.05em;
    }
    
    .bl_sizeBtn_wrap > * + * {
      margin-left: 10px;
    }
    
    .bl_sizeBtn {
      background-color: #ddd;
      border-radius: 4px;
      color: #666;
      padding: 5px;
      transition: opacity 0.4s;
    }
    
    .bl_sizeBtn:first-of-type {
      font-size: 13px;
    }
    
    .bl_sizeBtn:nth-of-type(2) {
      font-size: 16px;
    }
    
    .bl_sizeBtn:nth-of-type(3) {
      font-size: 19px;
    }
    
    /* 選択したボタンのスタイル */
    .bl_sizeBtn.is_active {
      background-color: #8cc779;
      color: #fff;
    }
    /****************************/
    /* ボタンのスタイルここまで */
    /****************************/
    
    .bl_sampleList {
      margin-top: 1em;
    }
    
    .bl_sampleList li {
      line-height: 1.7;
    }
    
    .bl_sampleList span {
      font-weight: 700;
      padding: 0 0.3em;
    }
    
    /* サイズ固定のテキスト */
    .bl_fzPx {
      font-size: 16px;
    }
    
    .el_lv2Heading {
      font-size: 2rem;
      font-weight: 700;
    }
    
    @media (hover: hover) and (pointer: fine) {
      .bl_headerList a:hover {
        color: #246a92;
      }
      
      .bl_sizeBtn:hover {
        opacity: 0.8;
      }
    }
  

フォントの単位はremで管理。
<body>には基本のフォントサイズとして、font-size: 1rem;を指定。
<html>に指定したfont-size: 100%;を、後ほど解説するjQueryで書き換えていきます。
なお、フォントサイズを変更したくない部分には、remではなくpxで指定してください。

1-3. jQuery + jquery-cookie

jQueryの後にjquery.cookie.jsを読み込みます。
CDNもしくは、ファイルダウンロードのどちらでも可です。

jquery-cookie
CDN
https://cdnjs.com/libraries/jquery-cookie
ダウンロード
https://github.com/carhartl/jquery-cookie

  
    // 文字サイズ変更ボタン
    $(function () {
      // クッキー(fontSize)があれば読み込む
      let fz = $.cookie('fontSize');

      if (fz) {
        // サイズ変更ボタンから背景色と文字色のCSSを外す
        $('.bl_sizeBtn').removeClass('is_active');
        
        // クッキーに保存されたidと一致したら適用
        if (fz == 'fz_sm') {
          $('html').css('font-size', '80%');
          $('#fz_sm').addClass('is_active');
        } else if (fz == 'fz_md') {// デフォルトサイズ
          $('html').css('font-size', '100%');
          $('#fz_md').addClass('is_active');
        } else if (fz == 'fz_lg') {
          $('html').css('font-size', '120%');
          $('#fz_lg').addClass('is_active');
        }
      }
      
      //サイズ変更時にクッキーへ保存
      $('.bl_sizeBtn').click(function () {
        // クリックされたbuttonのidをクッキー(fontSize)に保存(有効期限は7日)
        $.cookie('fontSize', this.id, { expires: 7 });
        
        // サイズ変更ボタンから背景色と文字色のCSSを外す
        $('.bl_sizeBtn').removeClass('is_active');
        
        // クリックされたbuttonのidと一致したら適用
        if (this.id == 'fz_sm') {
          $('html').css('font-size', '80%');
          $(this).addClass('is_active');
        } else if (this.id == 'fz_md') {// デフォルトサイズ
          $('html').css('font-size', '100%');
          $(this).addClass('is_active');
        } else if (this.id == 'fz_lg') {
          $('html').css('font-size', '120%');
          $(this).addClass('is_active');
        }
      });
    });
  

クリックイベントでは以下の処理を行なっています。

  • クリックされたボタンのidをクッキーに保存
  • 全体のフォントサイズ変更
  • ボタンのスタイル変更

クリックされたボタンのidをクッキーに保存。

  
    $.cookie('name', 'value', { expires: 7 });
  

サンプルでは以下の部分です。

  
    $.cookie('fontSize', this.id, { expires: 7 });
  

各引数について

第1引数にキー(name)。
→保存するクッキーの名前で今回は「fontSize」と命名。
第2引数に値(value)。
→今回はクリックされたボタンのidが入ります。
this.idで要素のidが取得できます。
第3引数には任意のオプションを追加できます。
expiresでクッキーを保存する日数を決められます。
expires: 7なら有効期限は7日。
expiresを指定しない場合は保存されないので、ユーザーがブラウザを閉じるとクッキーは削除されます。

その他オプションはGitHubに記載。
https://github.com/carhartl/jquery-cookie

expiresを設定することで、次回サイト訪問時はクリックイベントで保存されたクッキーを呼び出します。
クッキー読み込みの記述↓

  
    $.cookie('name');
  

サンプルでは以下の部分です。

  
    let fz = $.cookie('fontSize');
  

その後のif (fz)以降で保存されたクッキーの値(id)と一致する条件が見つかったら、該当のフォントサイズとボタンスタイルが適用されます。

  
    if (fz) {
      // サイズ変更ボタンから背景色と文字色のCSSを外す
      $('.bl_sizeBtn').removeClass('is_active');
      
      // クッキーに保存されたidと一致したら適用
      if (fz == 'fz_sm') {
        $('html').css('font-size', '80%');
        $('#fz_sm').addClass('is_active');
      } else if (fz == 'fz_md') {// デフォルトサイズ
        $('html').css('font-size', '100%');
        $('#fz_md').addClass('is_active');
      } else if (fz == 'fz_lg') {
        $('html').css('font-size', '120%');
        $('#fz_lg').addClass('is_active');
      }
    }
  

フォントの拡大縮小率を変えたい時は%の部分を変えてみてください↓

  
    $('html').css('font-size', '〇〇%');
  

【2】まとめ

まとめ

フォントサイズ変更機能について解説しました。
今回は大中小の3つを実装しましたが、個人的に「この機能って必要?」っていうのが正直なところでした。
何故ならブラウザ自体にフォントサイズ変更の機能があるため、そこからユーザー自身がちょうど良いサイズに設定して閲覧することが可能なためです。

まとめ

とはいえ、Webに慣れていない人がその設定を探すのは難しい場合もあるかと思いますので、一概に不要とは言えないのかもしれません。

最後にまとめたサンプルコードを貼っておきます(HTMLはトップページのみ)。

  
    <html lang="ja">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        <title>文字サイズ変更デモサイト</title>
        <meta name="robots" content="noindex">
        <!-- リセットCSS -->
        <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/destyle.css@1.0.15/destyle.css">
        <style>
          html {
            font-size: 100%;/* ここをjQueryで書き換えます */
            /* ↑解説のために指定していますが、デフォルトは100%なので通常は指定不要です */
          }
          
          body {
            color: #2C2C2C;
            font-family: "Helvetica Neue", "Helvetica", "Hiragino Sans", "Hiragino Kaku Gothic ProN", "Arial", "Yu Gothic", "Meiryo", sans-serif;
            font-size: 1rem;/* remで指定(1rem = 16px) */
            line-height: 1;
          }
          
          a {
            transition: color 0.4s;
          }
          
          .ly_siteWrapper {
            display: flex;
            flex-direction: column;
            min-height: 100vh;
          }
          
          .ly_header {
            padding: 15px 56px;
          }
          
          .ly_header_inner {
            display: flex;
            align-items: center;
            justify-content: space-between;
            width: min(100%, 880px);
            margin: 0 auto;
          }
          
          .ly_main {
            background-color: #fafafa;
            flex: 1;
            overflow-x: hidden;
          }
          
          .ly_section {
            padding: 90px 0;
          }
          
          .ly_section_inner {
            padding: 0 15px;
            text-align: center;
            width: min(100%, 880px);
            margin: 0 auto;
          }
          
          .bl_headerList {
            display: flex;
            align-items: center;
            justify-content: space-between;
          }
          
          .bl_headerList > * + * {
            margin-left: 56px;
          }
          
          .bl_headerList a {
            line-height: 1.5;
            padding: 10px;
          }
          
          /********************/
          /* ボタンのスタイル */
          /********************/
          .bl_sizeBtn_wrap {
            display: inline-flex;
            align-items: flex-end;
            font-weight: 500;
          }
          
          .bl_sizeBtn_wrap > span {
            font-size: 14px;
            letter-spacing: 0.05em;
          }
          
          .bl_sizeBtn_wrap > * + * {
            margin-left: 10px;
          }
          
          .bl_sizeBtn {
            background-color: #ddd;
            border-radius: 4px;
            color: #666;
            padding: 5px;
            transition: opacity 0.4s;
          }
          
          .bl_sizeBtn:first-of-type {
            font-size: 13px;
          }
          
          .bl_sizeBtn:nth-of-type(2) {
            font-size: 16px;
          }
          
          .bl_sizeBtn:nth-of-type(3) {
            font-size: 19px;
          }
          
          /* 選択したボタンのスタイル */
          .bl_sizeBtn.is_active {
            background-color: #8cc779;
            color: #fff;
          }
          /****************************/
          /* ボタンのスタイルここまで */
          /****************************/
          
          .bl_sampleList {
            margin-top: 1em;
          }
          
          .bl_sampleList li {
            line-height: 1.7;
          }
          
          .bl_sampleList span {
            font-weight: 700;
            padding: 0 0.3em;
          }
          
          /* サイズ固定のテキスト */
          .bl_fzPx {
            font-size: 16px;
          }
          
          .el_lv2Heading {
            font-size: 2rem;
            font-weight: 700;
          }
          
          @media (hover: hover) and (pointer: fine) {
            .bl_headerList a:hover {
              color: #246a92;
            }
            
            .bl_sizeBtn:hover {
              opacity: 0.8;
            }
          }
        </style>
      </head>
      <body>
        <div class="ly_siteWrapper">
          <header class="ly_header">
            <div class="ly_header_inner">
              <nav class="bl_headerNav" aria-label="サイト内メニュー">
                <ul class="bl_headerList">
                  <li>
                    <a href="#">TOPページ</a>
                  </li>
                  <li>
                    <a href="#">下層ページ1</a>
                  </li>
                  <li>
                    <a href="#">下層ページ2</a>
                  </li>
                </ul>
              </nav>
              <div class="bl_sizeBtn_wrap">
                <span>文字サイズ変更</span>
                <button type="button" class="bl_sizeBtn" id="fz_sm">小</button>
                <button type="button" class="bl_sizeBtn is_active" id="fz_md">中</button>
                <button type="button" class="bl_sizeBtn" id="fz_lg">大</button>
              </div>
            </div>
          </header>
          <main class="ly_main">
            <section class="ly_section">
              <div class="ly_section_inner">
                <h2 class="el_lv2Heading">TOPページです。</h2>
                <ul class="bl_sampleList">
                  <li>ここのフォントサイズは<span>rem</span>指定です(1rem)。</li>
                  <li class="bl_fzPx">ここのフォントサイズは<span>px</span>指定です(16px)。</li>
                </ul>
              </div>
            </section>
          </main>
        </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery-cookie/1.4.1/jquery.cookie.min.js" integrity="sha512-3j3VU6WC5rPQB4Ld1jnLV7Kd5xr+cq9avvhwqzbH/taCRNURoeEpoPBK9pDyeukwSxwRPJ8fDgvYXd6SkaZ2TA==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
        <script>
          // 文字サイズ変更ボタン
          $(function () {
            // クッキー(fontSize)があれば読み込む
            let fz = $.cookie('fontSize');
            
            if (fz) {
              // サイズ変更ボタンから背景色と文字色のCSSを外す
              $('.bl_sizeBtn').removeClass('is_active');
              
              // クッキーに保存されたidと一致したら適用
              if (fz == 'fz_sm') {
                $('html').css('font-size', '80%');
                $('#fz_sm').addClass('is_active');
              } else if (fz == 'fz_md') {// デフォルトサイズ
                $('html').css('font-size', '100%');
                $('#fz_md').addClass('is_active');
              } else if (fz == 'fz_lg') {
                $('html').css('font-size', '120%');
                $('#fz_lg').addClass('is_active');
              }
            }
            
            //サイズ変更時にクッキーへ保存
            $('.bl_sizeBtn').click(function () {
              // クリックされたbuttonのidをクッキー(fontSize)に保存(有効期限は7日)
              $.cookie('fontSize', this.id, { expires: 7 });
              
              // サイズ変更ボタンから背景色と文字色のCSSを外す
              $('.bl_sizeBtn').removeClass('is_active');
              
              // クリックされたbuttonのidと一致したら適用
              if (this.id == 'fz_sm') {
                $('html').css('font-size', '80%');
                $(this).addClass('is_active');
              } else if (this.id == 'fz_md') {// デフォルトサイズ
                $('html').css('font-size', '100%');
                $(this).addClass('is_active');
              } else if (this.id == 'fz_lg') {
                $('html').css('font-size', '120%');
                $(this).addClass('is_active');
              }
            });
          });
        </script>
      </body>
    </html>
  

人気記事Webサイトにフォントサイズ変更ボタンを実装する方法(jQuery使用)

人気記事【脱jQuery】スクロールしたら画面上部に追従メニューを表示する方法