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?

More than 3 years have passed since last update.

divをクリックしてタイムピッカーを起動させたい

Posted at

type="time"

<input type="time">

input要素のtype属性にtimeを指定することで、入力される値は時間の形式になる。
このインプットをクリックするとタイムピッカーが起動する。
step01_pc.jpg

Androidだとこんな感じ。
step01_mobile_1.jpg

いろんなとこでタイムピッカーを使いたい

Windowsはさておき、Androidの方は直感的に操作できてけっこう便利。
という訳で<div>とか、なにかしら要素をクリックしたときにタイムピッカーが起動して時刻が入力できるようにしたい。
もちろんJavaScriptで値も取得したい。

作りたいもの

今回は<div>で作ったボタンをクリックするとタイムピッカーが起動して、入力した時刻がボタンに表示される。っていうのをつくる。
機能としては<input>と変わらないけどデザインの自由度は<input>よりも大きいはず。

作成方法

jQueryとかは別として、どうやらタイムピッカーを<input type="time">以外で起動させる方法はなさそう。
最初は、何か要素をクリックしたらJavaScriptで強制的に<input>をクリックさせてタイムピッカーを起動させようとしたもののWindowsの方で失敗。Androidの場合は<input>をタップするとタイムピッカーが起動するけど、Windowsだと時計のアイコンをクリックしないといけないので、そこで躓いた。
いろいろ調べてみると、<input>の中のアイコンは操作できるらしいので、<input>をボタン内部いっぱいにして透明にして隠しておく方針に変更。
アイコンの操作は以下二つのサイトを参考にした。

https://blog.tmyt.jp/entry/2020/06/24/012442
https://itokoba.com/archives/301

ボタンを作成

ボタンとして<div>を設置。<input>は中に入れて見えないように透明に。CSSはボタンぽくサクッと整える。

html
<div id="button">
 <input type="time">
</div>
css
# button {
 width: 400px;
 height: 100px;
 border-radius: 20px;
 background-color: #2dbed5;
 box-shadow: 0 5px 10px #09262a;
}

/*クリック時の動き*/
# button:active {
 box-shadow: none;
 background-color: #2397aa;
 top: 5px;
}

input {
 height: 100%;
 width: 100%;
 border: none;
 opacity: 0;
}

/*どこをクリックしてもタイムピッカーが起動するようにする*/
input[type="time"]::-webkit-calendar-picker-indicator {
 margin: 0;
 padding: 0;
 height: 100%;
 width: 100%;
}

時刻を表示する

ボタンに時刻を表示するために<span>を追加。
JavaScriptで値を受け取って表示させれば完成。
このとき、ボタンや<input>にもCSSを加えて、要素の重なりを指定しておかないと<input>より<span>が上になってしまい、<input>がクリックできなくなるので注意。
以下のサイトを参考にした。

https://www.codegrid.net/articles/z-index-1

html
<div id="button">
 <input type="time">
 <span>00:00</span> <!-- 追加 -->
</div>
css
/*cssに追加*/

# button {
 position: relative;
 z-index: 1;
}

input {
 position: absolute;
 z-index: 2;
}

span {
 font-size: 80px;
 user-select: none;
 position: absolute;
 z-index: 1;
 top: 50%;
 left: 50%;
 transform: translateY(-50%) translateX(-50%);
 -webkit-transform: translateY(-50%) translateX(-50%);
}
js
let input = document.querySelector('input');
let time = document.querySelector('span');
input.addEventListener("input",  () => time.innerHTML = input.value, false);
1
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
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?