LoginSignup
3
2

More than 5 years have passed since last update.

フォントサイズ変更jsを作ってみたメモ

Last updated at Posted at 2018-04-27

前提条件

  • 拡大ボタンをクリックすると文字サイズが大きくなる。
  • 拡大は5回行える。
  • 標準ボタンをクリックすると最小サイズになる。
  • 標準ボタンをクリック時と5段階目の時に拡大ボタンをクリックするとアラートが表示される。
  • Cookieの保存は「cookies.js」を使用

ボタン作成

HTML

<ul>
  <li><button type="button" id="js-fs-normal">標準</button></li>
  <li><button type="button" id="js-fs-large">拡大</button></li>
</ul>

CSS

button {
  font-size: 100%;
}
.is-fs-m {
  font-size: 120%;
}
.is-fs-l {
  font-size: 140%;
}
.is-fs-xl {
  font-size: 160%;
}
.is-fs-xxl {
  font-size: 180%;
}
.is-fs-xxxl {
  font-size: 200%;
}

JavaScript


//標準ボタンのHTML取得
const BtnFsNormal = document.getElementById('js-fs-normal');
//拡大ボタンのHTML取得
const BtnFsLarge = document.getElementById('js-fs-large');
// htmlタグ取得
const RootTag = document.documentElement;
// alert出力文
const MaxMessage = encodeURIComponent('これ以上文字のサイズを大きくできません。');
const ResetMessage = encodeURIComponent('標準文字サイズに戻しますか?');

//拡大回数カウント用
let fsUpCount = 0;

// 標準ボタン
BtnFsNormal.addEventListener('click', function(){
  setFsReset();
  return false;
});
// 拡大ボタン
BtnFsLarge.addEventListener('click', function(){
  setFsUp();
  return false;
});

function setFsUp(){
  if(fsUpCount === 5) {
    alert(decodeURIComponent(MaxMessage));
  }else if(fsUpCount === 4) {
    RootTag.classList.add('is-fs-xxxl');
    RootTag.classList.remove('is-fs-xxl');
    fsUpCount = 5;
  }else if(fsUpCount === 3) {
    RootTag.classList.add('is-fs-xxl');
    RootTag.classList.remove('is-fs-xl');
    fsUpCount = 4;
  }else if(fsUpCount === 2) {
    RootTag.classList.add('is-fs-xl');
    RootTag.classList.remove('is-fs-l');
    fsUpCount = 3;
  }else if(fsUpCount === 1) {
    RootTag.classList.add('is-fs-l');
    RootTag.classList.remove('is-fs-m');
    fsUpCount = 2;
  }else if(fsUpCount === 0) {
    RootTag.classList.add('is-fs-m');
    fsUpCount = 1;
  }else if(fsUpCount === null) {
    RootTag.classList.add('is-fs-m');
    fsUpCount = 1;
  }
  BtnFsNormal.classList.remove('is-active');
  BtnFsLarge.classList.add('is-active');

  // cookieに保存
  docCookies.setItem('fsCookies', fsUpCount, 30, '/');
}

function setFsReset(){
  let resetModal = confirm(decodeURIComponent(ResetMessage));
  if (resetModal) {
    fsUpCount = 0;
    RootTag.removeAttribute('class');
  }
  // cookieに保存
  docCookies.setItem('fsCookies', fsUpCount, 30, '/');
}

function getCookie(){
  fsUpCount = docCookies.getItem('fsCookies');
  if(fsUpCount > 0) {
    setFsUp();
  }
}

window.addEventListener('load', getCookie, false);

実際作成した物

See the Pen フォントサイズ変更jsを作ってみたメモ by vent@青眼鏡君 (@vent2015) on CodePen.

3
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
3
2