いつもお世話になっています。下記の質問についてご存知の方がいらっしゃいましたらご教示を願います。
【質問の主旨】
index.htmlにdivタグがあります。そのdivタグはピンク色の背景をしたボックスになっています。JavaScriptを用いて、ボックスをクリックしたときに一瞬だけオレンジに変更するためにはどうすれば良いでしょうか?
【質問の補足】
1. プログラムの仕様について
今回の質問はドットインストールが主催しているイベントの仕様にもとづき投稿しました。
JavaScriptで『3つの箱』に動きを付けてみよう|256times|note
2. コードについて
仕様を満たすために自分が記述したHTML/CSS/JSファイルは以下の通りです。
JavaScript (js/main.js)
背景色を切り替えるためのJavaScriptコードについて以下の通り記述しています。
"use strict"; { const box1 = document.getElementById('box1'); const box2 = document.getElementById('box2'); const box3 = document.getElementById('box3'); let i = 0 function styleBackground() { box1.style.background = 'orange'; if (ox1.style.background === 'orange') { // backgroundが'orange'であれば'pink'に戻す box1.style.background = 'pink'; } } box1.addEventListener('click', () => { styleBackground(); }); box2.addEventListener('click', () => { box2.textContent = i++; }); box3.addEventListener('click', () => { box3.textContent = Math.floor(Math.random() * 6) + 1; }); }
HTML (index.html)
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <link rel="stylesheet" href="css/style.css"> <title>Document</title> </head> <body> <div id="container"> <div id="box1">Hello</div> <div id="box2">1</div> <div id="box3">Dice!</div> </div> <script src="js/main.js"></script> </body> </html>
CSS(css/style.css)
#container { display: flex; } #box1 { background: pink; width: 100px; height: 100px; margin-right: 20px; text-align: center; line-height: 96px; user-select: none; } #box2 { background: pink; width: 100px; height: 100px; margin-right: 20px; text-align: center; line-height: 96px; user-select: none; } #box3 { background: pink; width: 100px; height: 100px; margin-right: 20px; text-align: center; line-height: 96px; user-select: none; }
3. そのほか
3週間ほど前にスタック・オーバーフローでも同様の質問をしましたが、まだ回答を得られないためこちらで質問をさせていただきました。そのURLは以下の通りです。
以上、ご確認のほどをよろしくお願い申し上げます。
回答4件
あなたの回答
tips
プレビュー