カラー選択ボックス (カラーピッカー) で選択したカラーの値を取得する - HTML

カラー選択ボックス (カラーピッカー) で選択したカラーの値を取得するJavaScirptコードを取得します。

概要

カラー選択ボックス (カラーピッカー) で選択したカラーの値を取得するには、カラー選択ボックスのDOM要素を取得し、valueプロパティの値を取得します。

プログラム

コード

以下のHTMLファイルを作成します。
<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title></title>
  <script type="text/javascript">
    function buttonClick() {
      var elem = document.getElementById("colorInput");
      var outelem = document.getElementById("output");
      outelem.innerHTML = elem.value;
      var outelembox = document.getElementById("outColorBox");
      outelembox.style.backgroundColor = elem.value;
    }
  </script>
</head>
<body>
  <h2>カラーピッカーのデモ</h2>

  <form>
    <div>
      <input type="color" id="colorInput" />
      <label for="colorInput">カラー</label>
    </div>
    <button type="button" onclick="buttonClick();">Get Value</button>
    <hr />
    <div id="output">(color)</div>
    <div style="border:1px solid #808080; width:96px;height:96px;" id="outColorBox"></div>
  </form>
</body>
</html>

解説

カラー選択ボックス(カラーピッカー)とラベルを配置します。 カラー選択ボックスのタグの詳細についてはこちらの記事 を参照して下さい。
  <div>
    <input type="color" id="colorInput" />
    <label for="colorInput">カラー</label>
  </div>

ボタンを配置します。サブミットボタンとして動作しないよう type="button" を記述します。ボタンをクリックすると、buttonClick()関数を呼び出します。
  <button type="button" onclick="buttonClick();">Get Value</button>

buttonClick()関数のコードは以下です。
    function buttonClick() {
      var elem = document.getElementById("colorInput");
      var outelem = document.getElementById("output");
      outelem.innerHTML = elem.value;
      var outelembox = document.getElementById("outColorBox");
      outelembox.style.backgroundColor = elem.value;
    }

getElementById メソッドを呼び出してカラー選択ボックスの要素を取得します。
  var elem = document.getElementById("colorInput");

outputの要素を取得し、innerHTMLプロパティに内部のテキストにカラー選択ボックスで選択したカラーの値を代入して設定します。
  var outelem = document.getElementById("output");
  outelem.innerHTML = elem.value;

outColorBoxの要素を取得し、styleプロパティのbackgroundColor にカラー選択ボックスで選択したカラーの値を代入して、 カラー選択ボックスで選択したカラーを背景色に設定します。
  var outelembox = document.getElementById("outColorBox");
  outelembox.style.backgroundColor = elem.value;

実行結果

上記のHTMLファイルをWebブラウザで表示します。下図のページが表示されます。


カラー選択ボックスをクリックします。下図のカラーピッカーダイアログがポップアップ表示されます。


カラーピッカーでカラーを選択します。


[Get Value]ボタンをクリックします。


選択したカラーコードがページ下部に表示され、ボックスの背景色がカラー選択ボックスで選択したカラーに変わります。


別のカラーを選択して[Get Value]ボタンをクリックします。カラー選択ボックスで選択したカラーの情報が反映されます。


著者
iPentecのメインデザイナー
Webページ、Webクリエイティブのデザインを担当。PhotoshopやIllustratorの作業もする。
掲載日: 2023-02-15
iPentec all rights reserverd.