LoginSignup
0
0

More than 5 years have passed since last update.

baserJSでセレクトボックスを装飾する

Posted at

コーポレートサイトにちょうどいいJavaScriptライブラリ baserJS の解説記事です。

Webサイトと詳しいAPIリファレンスはこちら baserJS Webサイト

装飾のための要素を追加する

input要素を装飾する場合、CSSのappearance: noneなどを使用すれば、ある程度の装飾はできますが、ブラウザの対応だったり、痒いところに手が届かなかったり、デザインによっては満足に実装できないケースがあります。

baserJSのbcSelectメソッドは、実行するとセレクトボックスに対して、装飾のための要素を追加することができます。

HTML

<select name="pref" id="pref">
  <option selected>都道府県</option>
  <option value="1">北海道</option>
 . . .
  <option value="47">沖縄県</option>
</select>

JavaScript

$('select').bcSelect();

上記のJavaScriptを実行するとHTMLは以下のように変化します。

付加されるクラス名は変更可能です。

<span class="-bc-form-element -bc-wrapper -bc-form-select-wrapper -bc-wrapper--blur">
  <select name="pref" id="pref" class="-bc-element -bc-form-element -bc-form-select -bc-form-element--blur">
    <option selected="">都道府県</option>
    <option value="1">北海道</option>
    . . .
    <option value="47">沖縄県</option>
  </select>
  <label for="pref" class="-bc-form-element -bc-form-element__label -bc-form-select__label -bc-form-element__label--blur">
    <a href="#" class="-bc-form-element -bc-pseudo-select -bc-pseudo-select--blur">
      <span class="-bc-form-element -bc-pseudo-select__selected-display">都道府県</span>
      <ul class="-bc-form-element -bc-pseudo-select__option-list">
        <li class="-bc-form-element -bc-option-list__item -bc-option-list__item--selected" aria-selected="true">都道府県</li>
        <li class="-bc-form-element -bc-option-list__item -bc-option-list__item--unselected" aria-selected="false">北海道</li>
        . . .
        <li class="-bc-form-element -bc-option-list__item -bc-option-list__item--unselected" aria-selected="false">沖縄県</li>
      </ul>
    </a>
  </label>
</span>

状態変化

要素の一部には自動でイベントが登録され、状態によって変化します。この変化を利用して、CSS側で装飾の変化を記述するとよいでしょう。

フォーカス時のクラス

  • -bc-wrapper--blur ←→ -bc-wrapper--focus
  • -bc-form-element--blur ←→ -bc-form-element--focus
  • -bc-form-element__label--blur ←→ -bc-form-element__label--focus
  • -bc-pseudo-select--blur ←→ -bc-pseudo-select--focus

選択時のクラス

  • -bc-option-list__item--unselected ←→ -bc-option-list__item--selected

チェック時の属性

  • aria-selected="false" ←→ aria-selected="true"

サンプル

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