DOMContentLoadedが必要なケースはどのような場合でしょうか?
js
1'use strict'; 2 3{ 4 5 const words = [ 6 'apple', 7 'sky', 8 'blue', 9 'middle', 10 'set', 11 ]; 12 13 let word = words[Math.floor(Math.random() * words.length)]; 14 let loc = 0; 15 let score = 0; 16 let miss = 0; 17 const timeLimit = 3 * 1000; 18 let startTime; 19 const target = document.getElementById('target'); 20 const scoreLabel = document.getElementById('score'); 21 const missLabel = document.getElementById('miss'); 22 const timerLabel = document.getElementById('timer'); 23 let isPlaying = false; 24 25 26 function updateTarget(){ 27 let placeholder = ''; 28 29 for(let i = 0; i < loc; i++){ 30 placeholder += '_'; 31 } 32 target.textContent = placeholder + word.substring(loc); 33 } 34 35 function updateTimer(){ 36 const timeLeft = startTime + timeLimit - Date.now(); 37 timerLabel.textContent = (timeLeft / 1000).toFixed(2); 38 39 const timeoutId = setTimeout(() => { 40 updateTimer(); 41 },10); 42 43 if(timeLeft < 0){ 44 isPlaying = false; 45 clearTimeout(timeoutId); 46 timerLabel.textContent = '0.00'; 47 setTimeout(() => { 48 alert('Game Over'); 49 },100); 50 } 51 } 52 53 window.addEventListener('click', () => { 54 if(isPlaying === true){ 55 return; 56 } 57 58 isPlaying = true; 59 60 updateTarget(); 61 startTime = Date.now(); 62 updateTimer(); 63 }); 64 65 window.addEventListener('keyup',e =>{ 66 if(isPlaying !== true){ 67 return; 68 } 69 if(e.key === word[loc]){ 70 loc++; 71 72 if(loc === word.length){ 73 word = words[Math.floor(Math.random() * words.length)]; 74 loc = 0; 75 } 76 77 score++; 78 scoreLabel.textContent = score; 79 updateTarget(); 80 }else{ 81 miss++; 82 missLabel.textContent = miss; 83 } 84 85 }); 86 87 88}
<!DOCTYPE html> <html lang="ja"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Typing Game</title> <link rel="stylesheet" href="css/style.css"> </head> <body> <p id="target">click to start</p> <p class="info"> Letter count<span id="score">0</span>, Miss count: <span id="miss">0</span>, Time left:<span id="timer">0</span> </p> <script src="js/main.js"></script> </body> </html>
上記のjavascriptのコードは簡易なタイピングゲームを作成したものです。
疑問な点なのですが、javascriptのファイルの方では、document.getElementByIdによって、HTML要素を取得していますが、DOMContentLoadedによってHTMLを読み込まずにいるにもらず、何故要素を取得できるのでしょうか?

回答2件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2019/08/16 06:47 編集
2019/08/16 06:53 編集
2019/08/16 06:54
2019/08/16 06:55
2019/08/16 07:05