4
0

More than 1 year has passed since last update.

HTML ボタン作成方法一覧(a,input,button,divタグ)

Last updated at Posted at 2022-09-06

実現方法一覧

※実装例は「link foot」ボタンを押すと画面下に移動し、
「clickEvent」を押すとボタンの見た目「on」「off」が切り替わる仕組みです
また、formのsubmitイベントが発火した場合はイベント名がアラートで表示されます。
また、各ボタンの疑似要素:afterに「>」を表示するように設定しています。

aタグ

クリックにより別ページまたはアンカーに移動させたい場合などにaタグをボタンの見た目にする。
他にもサーバにデータを送信しないような汎用的なボタンを作成する際に使用する。

See the Pen Untitled by Komono masaya (@masayakomono) on CodePen.

inputタグ[type=button]

当初から存在するボタン要素、このボタンそのものに対し既定の動作は存在しない。
javascliptでclickイベントなどに対し個別に処理を実装する必要がある。

See the Pen Untitled by Komono masaya (@masayakomono) on CodePen.

inputタグ[type=submit]

input[type=button]にsubmitイベントの発火を付け加えたもの

See the Pen button-3 by Komono masaya (@masayakomono) on CodePen.

buttonタグ

HTML5より追加されたボタン要素
大まかにはinput[type=submit]と同様
inputタグには疑似要素を使うことができないが、buttonタグの場合は
:afterのような疑似要素を使用したcssの指定が可能

See the Pen button-4 by Komono masaya (@masayakomono) on CodePen.

divタグ

divタグでボタンっぽいものを作りclickイベントで拾う
・タブフォーカスが効かない
・エンターキーなどで押下できない
などの課題があり他のボタン要素と合わせようとすると手間がかかるためあまり推奨できない

See the Pen button-5-1 by Komono masaya (@masayakomono) on CodePen.

対応版※この例はキーボード押下でボタンを押すと「ボタンをキーでクリック」とアラートが表示されるように実装している

See the Pen button-5-2 by Komono masaya (@masayakomono) on CodePen.

まとめ

<a> <input>
[type=button]
<input>
[type=submit]
<button> <div>
HTML4以前利用可能 ×
submitイベント
(デフォルト)
× × ×
タブキーによるフォーカス
エンターキー等による押下
疑似要素利用可能 × ×

結論

・疑似要素を利用したデザインの事を考えるとaタグまたはbuttonタグを使用したほうが良い
・古いブラウザのことも検討するのであればinputタグの使用を検討する
・divタグで実現しようとする場合はtabindexやkeydownイベントなどをわざわざ実装する必要があり手間である。

参考URL

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