「JavaScript」カラーボタンで色の値を取得して背景の色を設定する

環境

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
Windows 10 home 64bit
Google Chrome 103.0.5060.134
Windows 10 home 64bit Google Chrome 103.0.5060.134
Windows 10 home 64bit
Google Chrome 103.0.5060.134

構文

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<input type="color" id="カラーボタンID名" />
const 変数名 = document.getElementById("カラーボタンID名");
<input type="color" id="カラーボタンID名" /> const 変数名 = document.getElementById("カラーボタンID名");
<input type="color" id="カラーボタンID名" />
const 変数名 = document.getElementById("カラーボタンID名");

変数名.addEventListener(“change", 関数名);
addEventListener() は EventTarget インターフェイスのメソッドで、ターゲットに特定のイベントが配信されるたびに呼び出される関数を設定します。

使用例

Plain text
Copy to clipboard
Open code in new window
EnlighterJS 3 Syntax Highlighter
<!DOCTYPE html>
<html>
<body>
<label>背景の色を指定 <input type="color" id="cftcolor" /></label>
<script>
const cr = document.getElementById("cftcolor");
cr.addEventListener("change", chgColor);
function chgColor() {
document.body.style.background = cr.value;
}
</script>
</body>
</html>
<!DOCTYPE html> <html> <body> <label>背景の色を指定 <input type="color" id="cftcolor" /></label> <script> const cr = document.getElementById("cftcolor"); cr.addEventListener("change", chgColor); function chgColor() { document.body.style.background = cr.value; } </script> </body> </html>
<!DOCTYPE html>
<html>
<body>

<label>背景の色を指定 <input type="color" id="cftcolor" /></label>

<script>
  const cr = document.getElementById("cftcolor");
  cr.addEventListener("change", chgColor);

  function chgColor() {
    document.body.style.background = cr.value;
  }
</script>

</body>
</html>

結果
カラーボタンで色(例緑)を指定して画面の背景全体の色(緑)を変更します。

JavaScript

Posted by arkgame