1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

セレクトボックスの選択肢の位置を変える

Posted at

はじめに

セレクトボックスの選択肢の位置を変えてほしいと依頼がありました。

どういうことかと言うと、
これを
image.png

こうしたい
image.png

調べてみる

  • option要素はwidthが効かない
  • optionではなくul、liタグを使おう

出来ないという情報しかない…

どうするか:thinking:

とりあえず、作ってみました。

See the Pen Untitled by masayasu_t (@cjlsrdxi-the-builder) on CodePen.

ソースを見ていただけば理解いただけると思いますが、見えているセレクトボックスの上に見えないセレクトボックスを重ねています。

つまり、こう言うことです。
image.png

見えないセレクトボックスは「opacity: 0;」で隠しています。

「visibility: hidden;」だとマウスイベントが取れませんが、「opacity: 0;」だと着火します。
なので、見えないセレクトボックスのエリアをクリックすると選択肢が表示されます。

そして、そのままでは選択したデータが見えているセレクトボックスに反映されないので、javascriptで選択した値を移しています。

おわりに

ここまでする必要があるのかと思いますが、「できません」ではつまらないので作ってみました。

「opacity: 0;」で隠すのは色々と応用できそうな気がします。

1
0
1

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
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?