有個需求,需要用到Div中隨機點分布,隨手寫了一個,最後發現需求變了,沒用到。
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%// 點數量int point_Count = 30;// div大小int div_Width = 180;int div_Height = 150;// 點大小int point_Width = 10;int point_Height = 10;// 儲存已經隨機出的點int[] left_Array = new int[point_Count];int[] top_Array = new int[point_Count];// 隨機類class Mice{public int randomNum(int MIN, int MAX){return new Random().nextInt(MAX - MIN + 1) + MIN; }}Mice mice = new Mice();%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html> <head> <title>Mice</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><style>.block {background-color: #009900;height: <%=point_Height%>px;width: <%=point_Width%>px;}</style> </head> <body> <div id="tprs" style="width:<%=div_Width%>px;height:<%=div_Height%>px;position:absolute;border:1px solid #c9d5ed;"> <% for(int i = 0;i < point_Count;i++){ int left = 0; int top = 0; // 隨機數需要注意 // 1 與點寬度/長度相加不能超出div範圍 // 2 不能出現點與點之間重疊的情況 // 隨機處理 boolean again = true; while(again){ left = mice.randomNum(0, div_Width); top = mice.randomNum(0, div_Height); // 2.1 隨機點不能超出div範圍 if(left > div_Width - point_Width || top > div_Height - point_Height){ again = true; continue; }else{ again = false; } // 對比已經存在的點資料 for(int j = 0;j < i;j++){ // 判斷四個頂點是否已經存在於已有節點中 // 左上頂點 int zb1_x = left; int zb1_y = top; // 右上頂點 int zb2_x = left + point_Width; int zb2_y = top; // 左下頂點 int zb3_x = left; int zb3_y = top + point_Height; // 右下頂點 int zb4_x = left + point_Width; int zb4_y = top + point_Height; // 已經存在的座標的範圍int left_FW = left_Array[j] + point_Width;int top_FW = top_Array[j] + point_Height;// 判斷標記boolean mark = false;if(zb1_x <= left_FW && zb1_x >= left_Array[j] && zb1_y <= top_FW && zb1_y >= top_Array[j]){mark = true;}if(zb2_x <= left_FW && zb2_x >= left_Array[j] && zb2_y <= top_FW && zb2_y >= top_Array[j]){mark = true;}if(zb3_x <= left_FW && zb3_x >= left_Array[j] && zb3_y <= top_FW && zb3_y >= top_Array[j]){mark = true;}if(zb4_x <= left_FW && zb4_x >= left_Array[j] && zb4_y <= top_FW && zb4_y >= top_Array[j]){mark = true;}if(mark){again = true; continue;} } } left_Array[i] = left; top_Array[i] = top; out.println("<div class='block' style='top:"+top+"px; left:"+left+"px; position:absolute'></div>"); } %></div> </body></html>
最終效果: