淄博开心果机械加工厂:Javascript不断随机生成正方形

来源:百度文库 编辑:偶看新闻 时间:2024/04/28 23:01:25

最终的代码: 

  [xhtml] view plaincopyprint?

  1.   
  2.   
  3.    
  4.    New Document   
  5.     
  6.     
  7.     
  8.     
  9.   
  10.     
  11.   #container{  
  12.     position:absolute;  
  13.     top:10px;  
  14.     left:80px;  
  15.     width:120px;  
  16.     height:300px;  
  17.     overflow:hidden;  
  18.     border:1px solid red;  
  19.     }  
  20.     
  21.   
  22.     
  23.     var interval;  
  24. /*  
  25.  *随机生成颜色  
  26.  *先生成红、绿、蓝三个基本色,再拼成类似#FF12A2的16进制的颜色值  
  27.  *如果随机生成的某个基本色的值是小于16的,则转成16进制的字符串时只有一位  
  28.  *所以这样的情况要在前面加‘0’  
  29. */  
  30.     function generateColor(){  
  31.         var color = ["#"];        
  32.         for(var i=0; i<3; i++){  
  33.             var randInt = Math.round(255 * Math.random());  
  34.             var hexColor = (randInt < 16 ?  "0" : "") + randInt.toString(16);  
  35.             color.push(hexColor);  
  36.         }  
  37.         return color.join("");  
  38.     }  
  39.   
  40.     function generateSquare(){  
  41.         var top = 300 * Math.random();  
  42.         var left = 120 * Math.random();  
  43.         var width = Math.round(100 * Math.random());  
  44.         var bgColor = generateColor();  
  45.         var borderStyle = Math.random() > 0.5 ? "solid" : "dotted";  
  46.         var borderColor = generateColor();  
  47.   
  48.         var square = document.createElement("div");  
  49.         square.style.position = "absolute";  
  50.         square.style.top = top + 'px';  
  51.         square.style.left = left + 'px';  
  52.         square.style.width = width + 'px';  
  53.         square.style.height = width + 'px';  
  54.         square.style.backgroundColor = bgColor;  
  55.         square.style.borderStyle = borderStyle;  
  56.         square.style.borderColor = borderColor;  
  57.         square.style.borderWidth = "1px";  
  58.         return square;  
  59.     }  
  60.   
  61.     function f() {  
  62.         var container = document.getElementById("container");   
  63.         container.appendChild(generateSquare());  
  64.     }  
  65.   
  66.     function randSquare(){    
  67.         interval = setInterval(f, 100);  
  68.     }  
  69.   
  70.     function control(){  
  71.         var btnCtrl = document.getElementById("btnCtrl");  
  72.         if(btnCtrl.value == "stop"){  
  73.             clearInterval(interval);  
  74.             btnCtrl.value = "goon";  
  75.         }  
  76.         else{  
  77.             interval = setInterval(f, 100);  
  78.             btnCtrl.value = "stop";  
  79.         }  
  80.     }  
  81.     
  82.    
  83.   
  84.    
  85.        
  86.   
  
  •     
  •    
  •