1
1

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.

シンプルなswitch checkboxを自作してみる

1
Last updated at Posted at 2015-10-18

背景

スイッチ可能チェックボックスを表現するにはいろいろな便利なライブラリーがありますが
それだけのためにライブラリー入れるのも嫌だし、文字を表示したりしたいこともあり、
angular directive作成の学習の意味も含めて自作してみました。

ソースはここにおいています。

出来上がったイメージ

オン
on
オフ
on

実際の動きは動作はデモページでどうぞ。

仕組み

スイッチのスライドはCSSで行っているのでスクリプトが殆どありません。
cssは兄弟セレクターと:checked擬似セレクターでチェックされた状態のスタイルを切り替えています。

.switchCheckbox input[type=checkbox]:checked + .switchBox .switchContainer
{
    height: 30px;
    margin-right: -30px;
    margin-left: 0;

    color: white;
    background-color: #007aff;
}

テンプレートも小さいのはそのままスクリプトで埋め組んでしまいます。

require: 'ngModel',
restrict: 'E',
template: '' +
    '<label class="switchCheckbox">' +
    '    <input type="checkbox">' +
    '    <div class="switchBox">' +
    '        <div class="switchContainer">' +
    '            <div class="on">ON</div>' +
    '            <div class="switch"></div>' +
    '            <div class="off">OFF</div>' +
    '        </div>' +
    '    </div>' +
    '</label>',

disabledの対応は属性をチェックしてイベントをキャンセルするようになっています。

cbx.on( 'click', function( evt ) {

    if ( attr.disabled ) {

        evt.preventDefault();
    }
});

最後にngModelControllerでモデルとビューの値を交互に設定してあげます。

注意点

angularのjqliteは要素検索の機能を大分削られているので要注意です。
例えばfindはタグ名でしか検索できないなどがあります。

いろいろ改良すべき点もありますが先ずは目標を達成できたのでここまでにします。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?