var sHeight = jQuery(document.body).outerHeight(true) - 100;
var sWidth = jQuery(document.body).outerWidth(true) - 100;
var div_top = GetRandomNum(0,sHeight);
var div_left = GetRandomNum(0,sWidth);
jQuery("#div").css("position","absolute");
jQuery("#div").css("z-index",100000);
jQuery("#div").css("top",div_top);
jQuery("#div").css("left",div_left);
function GetRandomNum(Min,Max)
{
var Range = Max - Min;
var Rand = Math.random();
return(Min + Math.round(Rand * Range));
}
該演算法簡單使用,併發訪問效能非常好。隨機概率
function get_rand($proArr)
{
$result = '';
//概率陣列的總概率精度
$proSum = array_sum($proArr);
//概率陣列迴圈
foreach ($proArr as $key => $proCur) {
$randNum = mt_rand(1, $proSum);
if ($randNum <= $proCur) {
$result = $key;
break;
} else {
$proSum -= $proCur;
}
}
unset($proArr);
return $result;
}
呼叫
//本次抽獎的獎項資訊,必須按照從大到小的順序進行填寫,id為獎次,gift為中獎資訊,v為中獎概率必須是整數,num為獎品數量
//需要注意的是,該處也必須包含不中獎的資訊,概率從小到大進行排序
$gift_arr = array(
'0' => array('id' => 1, 'gift' => '44元購買1G/年空間', 'v' => 1, 'num' => 1),
'1' => array('id' => 2, 'gift' => '55元購買1G/年空間', 'v' => 2, 'num' => 2),
'2' => array('id' => 3, 'gift' => '66元購買1G/年空間', 'v' => 5, 'num' => 2),
'3' => array('id' => 4, 'gift' => '77元購買1G/年空間', 'v' => 10, 'num' => 3),
'4' => array('id' => 5, 'gift' => '88元購買1G/年空間', 'v' => 15, 'num' => 4),
'5' => array('id' => 6, 'gift' => '99元購買1G/年空間', 'v' => 67, 'num' => 10)
);
foreach ($gift_arr as $val) {
$arr[$val['id']] = $val['v'];
}
//$rid中獎的序列號碼
$rid = $this->get_rand($arr); //根據概率獲取獎項id
$str = $gift_arr[$rid - 1]['gift']; //中獎項
中獎到達上限後,中的獎項換成不中獎,中的獎項發完換成不中獎