LoginSignup
4
2

More than 5 years have passed since last update.

Bootstrapのウィジェットを手抜きでRiot化

Last updated at Posted at 2017-12-16

Bootstrapのウィジェットを見ていたら、Riot.jsで動かすのもそう難しくないかなと思うところがありました。

「手抜き」の意味

「手抜き」と書きましたが、何の手を抜くのかといえば、「Bootstrap用のCSSをそのまま流用する」ということです。デザインにBootstrapを使っている場合、ウィジェット用のCSSまで一本になっているので、流用することにかかるコストはほぼありませんし、多くのウィジェットは「CSSで形が決まっていて、jQueryで主にやっているのはクラスの付替えだけ」という感じなので、同じHTML構造をRiotで作ればすぐできそうな感じです。

JavaScriptを見てみる

具体的に、ドロップダウンのJavaScriptを見てみましょう。実際に行っていることは、

  • 展開時…openクラスを追加する、aria-expanded=trueにする、必要ならバックドロップを入れる
  • 閉じる時…openクラスを外す、aria-expanded=trueにする、バックドロップを消す

実はこれだけで、あとはCSSの力で行っているのです。

Riotで再現

ということで、「本来のHTML構造」と「展開時/閉じる時の状態制御」さえあれば、Riotとして動かすことも問題なくできます。

dropdown-menu.tag
<dropdown-menu>
  <div class={dropdown: true, open: opened}>
    <button type="button" aria-haspopup="true" aria-expanded={opened ? 'true' : 'false'} onclick={onClickButton}>
      ドロップダウンボタン
      <span class="caret"></span>
    </button>
    <ul class="dropdown-menu" aria-labelledby="dLabel">
      <li each={item in items}>{item}</li>
    </ul>
  </div>
  <div class='dropdown-backdrop' if={opened && useBackDrop} onclick={hide}></div>

  <script>
    onClickButton(){
      this.opened = !this.opened
      document.body.addEventListener(/*
        略: 外側をクリックしたらthis.opened = falseに戻す
      */)
    }
    hide() {
      this.opened = false
    }
    this.items = ['foo', 'bar', 'baz']
    this.useBackDrop = 'ontouchstart' in document.documentElement
  </script>
</dropdown-menu>
4
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
4
2