7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

いい感じのトグルボタンを実装した

Posted at

はじめに

今回はサービス開発をする上でトグルボタンを実装することになり、「1から作るのめんどいのでいいサンプルパクれないかな」と思って探していたのですが、あまりいい感じのが見つかりませんでした。

僕の要望

  • input type="checkbox" をちゃんと利用しており、楽にフォームのチェックボックスとしても利用できる
  • jqueryを使用しない(動き的にもjsを利用するほどのものでもないと思うのでcssのみにしたい)
  • 再現性の高いコード(楽したい)

今回のゴール

toggle_button.gif

現実

codepenにいっぱい落ちているけど大体はどれか欠けている。他のサイトも大体変わらない印象。codepenは特にただボタンを実装すればいいことをいいことにposition:absolute;を利用しているのが多く参考にならない。

めんどくさいけどもう実装しよう...

いいなと思ったサイトのコードを部分的に拝借して作成しました。

実際のコードがコチラ

hoge.slim
 input#toggleButton1.toggle-button type="checkbox"
 label[for="toggleButton1"]
toggle.scss
.toggle-size {
  width: auto;
  max-width: 60px;
  height: auto;
  max-height: 50px;
}

.toggle-button {
  appearance: none;
  margin: 10px;
  width: 60px;
  height: 29px;
  border: 1px solid #B3B3B3;
  border-radius: 50px;
  background-color: #fff;
  transition: background-color .4s ease;
  &:focus {
      outline: none;
  }
  &:checked {
      background-color: #6468c3;
  }
}

.toggle-button + label {
  position: relative;
  display: inline-block;
  top: -45.5px;
  left: 1px;
  width: 27px;
  height: 27px;
  border: 1px solid #B3B3B3;
  border-radius: 50%;
  background-color: #fff;
  box-shadow: 0 0 4px rgba(0,0,0,0.4);
  transition: left .4s ease, background-color .4s ease;
}

.toggle-button:checked + label {
  position: relative;
  display: inline-block;
  top: -45.5px;
  left: 31px;
  width: 27px;
  height: 27px;
  border: 0px solid rgba(0,0,0,0.0);
  border-radius: 50%;
  box-shadow: 0 0 4px rgba(0,0,0,0.4);
}

実際に動いている様子

toggle_button.gif

もしかしたら不必要なコードが紛れ込んでいる可能性があるのであったら教えて頂けると助かります。
また注意点としてcssのtop: px;, left: px;等の値は自分の作成したい場所によってはへんな感じになると思いますが、数値を調整してあげることで使用することができます。

7
6
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
7
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?