上毛印刷株式会社

【JavaScript】iOS風トグルボタンを実装

【JavaScript】iOS風トグルボタンを実装

2025年12月22日
WEBサイト制作
  • #HTML
  • #css
  • #JavaScript
  • #tips

こんにちは!
上毛印刷WEB制作担当のソーヤです。

今回はメチャメチャニッチなtipsを紹介します。
アプリ開発なんかに使えますかね?

実装例

画面ロックパスワード

パスワードを4桁で設定してください

HTML例

<div class="content">
  <div class="switch">
    <strong>画面ロックパスワード</strong>
    <label>
      <input type="checkbox" id="lockToggle">
      <span class="slider"></span>
    </label>
  </div>
  <div class="device-pass" id="passwordArea">
    <p>パスワードを4桁で設定してください</p>
    <input type="tel" maxlength="4" placeholder="0000">
  </div>
  <button>OK</button>
</div>

CSS例

.content {
  background: #f4f4f4;
  width: 85%;
  max-width: 400px;
  margin: 100px auto;
  border-radius: 10px;
}
.switch {
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.switch label {
  position: relative;
  width: 50px;
  height: 30px;
}
.switch input {
  display: none;
}
.slider {
  position: absolute;
  inset: 0;
  background: #ddd;
  border-radius: 30px;
  cursor: pointer;
}
.slider::before {
  content: "";
  position: absolute;
  width: 26px;
  height: 26px;
  left: 2px;
  top: 2px;
  background: #fff;
  border-radius: 50%;
  transition: .3s;
}
input:checked + .slider {
  background: #3ae259;
}
input:checked + .slider::before {
  transform: translateX(20px);
}
.device-pass {
  overflow: hidden;
  background: #f4f4f4;
  max-height: 0;
  transition: max-height .6s ease;
  text-align: center;
}
.device-pass.open {
  max-height: 180px;
}
.device-pass p {
  margin-top: 15px;
}
.device-pass input {
  font-size: 18px;
  padding: 10px;
  width: 120px;
  text-align: center;
  margin: 0 0 20px;
}
button {
  width: 100%;
  padding: 12px;
  font-size: 16px;
  border: none;
  border-top: 1px solid #c9c9c9;
  background-color: #f4f4f4;
  border-bottom-right-radius: 10px;
  border-bottom-left-radius: 10px;
  color: #0090e9;
}

JavaScript例

const toggle = document.getElementById('lockToggle');
const passArea = document.getElementById('passwordArea');
toggle.addEventListener('change', () => {
  passArea.classList.toggle('open', toggle.checked);
});

まとめ

今回もjQueryではなく、Vanilla.jsで実装してみました。

コピペしてガンガン使ってください!

WEB制作担当ソーヤ

ソーヤ

上毛印刷WEB制作担当
東証プライム企業の本社WEB受託チームにてフロントエンドエンジニアの経験あり。


この記事に対するご意見・ご感想・ご質問等ありましたら、
ぜひ下記フォームにてお送りください。

    お名前必須
    メールアドレス必須
    お問い合わせ内容必須
    PAGE TOP