原生JS寫了一個小demo,根據輸入的數字生成不同背景顏色的小方塊兒~


昨天練習寫了這個小demo,個人覺得通過設置定位元素left和top的值,來實現換行的功能,這種方法很巧妙~

另外,如下代碼中的隨機顏色的獲取,還請各位前輩多多指教:需要改進的地方;或者有沒有更好的方法。

 

 1 <!DOCTYPE html>
 2 <html>
 3     <head>
 4         <meta charset="UTF-8">
 5         <title></title>
 6         <style type="text/css">
 7             body{text-align: center;}
 8             li{height:50px;width:50px;background:red;position:absolute;list-style:none;text-align: center;color:white;line-height:50px;}
 9         </style>
10         <script type="text/javascript">
11             window.onload=function(){
12                 var text1=document.getElementById("texta");
13                 var btn1=document.getElementById("btn");
14                 var ul1=document.getElementById("ul");            
15                 btn1.onclick=function(){
16                     for(var i=0;i<parseInt(text1.value);i++){
17                         
18                         var li1=document.createElement("li");
19                         li1.style.left=li1.offsetLeft+i%20*64+"px";
20                         li1.style.top=li1.offsetTop+parseInt(i/20)*64+64+"px";  // 實現換行
21                         li1.innerHTML=i+1;
22                         li1.style.background=random_load();
23                         ul1.appendChild(li1);
24                         
25                     }
26                 }
27             }
28             function random_load(){
29                 var R=hao(0,255).toString(16);  
30                 var G=hao(0,255).toString(16);
31                 var B=hao(0,255).toString(16);
32                 return "#"+aaa(R,G,B);
33             }
34             function hao(min,max){
35                   return parseInt(Math.random()*(max-min+1)+min)
36             }
37             function aaa(r,g,b){                  
38                   r=r.length==1?"0"+r:r;
39                   g=g.length==1?"0"+g:g;
40                   b=b.length==1?"0"+b:b;    //隨機會獲取到5位的十六進制數,不能作為顏色值,所以用這個方法解決,還請前輩多多指點  ^-^!
41                   return r+g+b;
42             }
43         </script>
44     </head>
45     <body>
46         <input type="text" name="texta" id="texta" value="" />
47         <input type="button" name="btn" id="btn" value="生成DIV" />
48         <ul id="ul">
49         </ul>
50     </body>
51 </html>

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM