三个金蛋、一把锤子及中奖结果#result_tip代码以下:
锤子
1 2 3
jQuery
1、当鼠标滑向金蛋时,锤子会仅靠金蛋右上方,经由过程position()来掌握位置。
$(".egg_list li").hover(function() {
var position_left = $(this).position().left + $(this).width();
$("#hammer").show().css('left', position_left);
})
当挥舞锤子砸向金蛋eggClick()前,我们先把金蛋中的数字编号隐蔽起来。
$(".eggList li").click(function() {
$(this).children("span").hide();
eggClick($(this));
});
末了,我们向背景ajax.php发送一个ajax要求,背景php顺序会处置惩罚奖项分派并把中奖结果返回。我们运用animate()来完成砸锤子的动画,经由过程转变锤子的top和left位子来完成简朴的动画结果,锤子砸下去后,金蛋款式变成.curruent,同时金花四溅,末了展示中奖结果,我们看下砸蛋的eggClick要领:
function eggClick(obj) {
$.get("ajax.php",function(data) {
if (obj.hasClass("current")) {
alert("蛋都碎了一地,革新从新来过吧!");
return false;
}
$(".hammer").css({
"top": obj.position().top - 55,
"left": obj.position().left + 185
});
$(".hammer").animate({
"top": obj.position().top - 25,
"left": obj.position().left + 125
},30, function() {
obj.addClass("current"); //蛋碎结果
obj.find("sup").show(); //金花四溅
$(".hammer").hide();
$('.result_tip').css({
display: 'block',
top: '100px',
left: obj.position().left + 45,
opacity: 0
}).animate({
top: '50px',
opacity: 1
},
300,
function() {
if (data.msg == 1) {
$("#result").html("祝贺您中得" + data.prize_title + "!");
} else {
$("#result").html("Sorry,您没能中奖!");
}
});
});
},
"json")
}
末了我们看下ajax.php中奖项设置和盘算中奖概率算法。
$prize_arr = array(
'0' => array('id' => 1, 'title' => 'iphone5s', 'v' => 5),
'1' => array('id' => 2, 'title' => '联络笔记本', 'v' => 10),
'2' => array('id' => 3, 'title' => '音箱装备', 'v' => 20),
'3' => array('id' => 4, 'title' => '30GU盘', 'v' => 30),
'4' => array('id' => 5, 'title' => '话费50元', 'v' => 10),
'5' => array('id' => 6, 'title' => 'iphone6s', 'v' => 15),
'6' => array('id' => 7, 'title' => '感谢,继承加油哦!~', 'v' => 10),
);
foreach ($prize_arr as $key => $val) {
$arr[$val['id']] = $val['v'];
}
$prize_id = getRand($arr); //依据概率猎取奖品id
$data['msg'] = ($prize_id == 7) ? 0 : 1; //假如为0则没中
$data['prize_title'] = $prize_arr[$prize_id - 1]['title']; //中奖奖品
echo json_encode($data);
exit; //以json数组返回给前端
function getRand($proArr) { //盘算中奖概率
$rs = ''; //z中奖结果
$proSum = array_sum($proArr); //概率数组的总概率精度
//概率数组轮回
foreach ($proArr as $key => $proCur) {
$randNum = mt_rand(1, $proSum);
if ($randNum <= $proCur) {
$rs = $key;
break;
} else {
$proSum -= $proCur;
}
}
unset($proArr);
return $rs;
}
经由过程ajax.php,我们能够看出共设置了7个奖项并设置了中奖概率,比方砸中”iphone5s“的概率占5%,砸不中的概率占10%,点击演示砸金蛋demo来尝尝你的命运运限吧。
演示下载地点:http://www.erdangjiade.com/js…