2016-03-22 16 views
0

このHTMLファイルには、like thisの中にカラフルなdivの四角形を作成すると思われるスクリプトタグがありますが、JavaScriptはオンロードでは表示されません。JavaScript divが動作しないwhileループ

<!DOCTYPE html> 
<html> 
<head> 
    <title>An Example Project</title> 
    <meta http-equiv="refresh" content="3"> 
    <style> 
     div {position:absolute} 
    </style> 

</head> 
<body id="theBody" onload="show_pattern()"> 
<script> 
     function show_pattern() { 
      var top_position = 25, left_position = 25; // set up variables 
      var width = 500, height = 500; 
      var color_list = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]; 
      var the_body = document.getElementById("theBody"); //add div node to body 

      while (width > 50) { 
       var this_div = document.createElement("div"); 
       var random_color = Math.random() * 7; //0-6.999 
       random_color = Math.floor(random_color); // 0-6 (7 total from list) 
       this_div.style.top = top_position + "px"; 
       this_div.style.left = left_position + "px"; 
       this_div.width = width + "px"; 
       this_div.style.height = height + "px"; 
       this_div.style.background = color_list[random_color]; 
       the_body.appendChild(this_div); 
       top_position += 10; 
       left_position += 10; 
       width -= 20; 
       height -= 20; 
    } 
} 
</script> 
</body> 
</html> 

答えて

0

正しく設定していません。それは

this_div.style.width = width + "px"; 
です。
0

コードにロジックエラーがある可能性があります。それ以外では正常に動作します。http://jsfiddle.net/usLv6rzh/

<body id="theBody" onload="show_pattern()"> 
<script> 
     function show_pattern() { 
      var top_position = 25, left_position = 25; // set up variables 
      var width = 500, height = 500; 
      var color_list = ["red", "orange", "yellow", "green", "blue", "indigo", "violet"]; 
      var the_body = document.getElementById("theBody"); //add div node to body 

      while (width > 50) { 
       var this_div = document.createElement("div"); 
       var random_color = Math.random() * 7; //0-6.999 
       random_color = Math.floor(random_color); // 0-6 (7 total from list) 
       this_div.style.top = top_position + "px"; 
       this_div.style.left = left_position + "px"; 
       this_div.width = width + "px"; 
       this_div.style.height = height + "px"; 
       this_div.style.background = color_list[random_color]; 
       the_body.appendChild(this_div); 
       top_position += 10; 
       left_position += 10; 
       width -= 20; 
       height -= 20; 
    } 
} 
</script> 
関連する問題