實現原理:當色子擲出后,通過jQuery的animate()函數改變色子位移,中間加入延時效果,并變換色子背景,最終動畫運行到隨機產生的點數時停止,并顯示擲出的點數。其實就是動畫過程加入多個不同圖片的幀(同flash動畫影片中的幀),幀數越多效果越好,然后逐幀運行后就形成了動畫效果。
一、準備工作
我們需要準備色子素材,本示例中,我采用從網絡上獲取到的色子素材,我們要做處理的是將6個色子圖片(1-6點),以及中間過渡效果的圖片(做運動模糊處理)放在同一張圖片上,保存為dice.png,用作色子背景圖。
載入jQuery庫,這是必須的。
復制代碼 代碼如下:
<script type="text/javascript" src="js/jquery.js"></script>
復制代碼 代碼如下:
<div></div>
<p>請直接點擊上面的色子!</p>
復制代碼 代碼如下:
.wrap{width:90px; height:90px; margin:120px auto 30px auto; position:relative}
.dice{width:90px; height:90px; background:url(dice.png) no-repeat;}
.dice_1{background-position:-5px -4px}
.dice_2{background-position:-5px -107px}
.dice_3{background-position:-5px -212px}
.dice_4{background-position:-5px -317px}
.dice_5{background-position:-5px -427px}
.dice_6{background-position:-5px -535px}
.dice_t{background-position:-5px -651px}
.dice_s{background-position:-5px -763px}
.dice_e{background-position:-5px -876px}
p#result{text-align:center; font-size:16px}
p#result span{font-weight:bold; color:#f30; margin:6px}
#dice_mask{width:90px; height:90px; background:#fff; opacity:0; position:absolute;
top:0; left:0; z-index:999}
復制代碼 代碼如下:
$(function(){
var dice = $("#dice");
dice.click(function(){
dice.attr("class","dice");//清除上次動畫后的點數
dice.css("cursor","default");
$(".wrap").append("<div></div>");//加遮罩
var num = Math.floor(Math.random()*6+1);//產生隨機數1-6
dice.animate({left: '+2px'}, 100,function(){
dice.addClass("dice_t");
}).delay(200).animate({top:'-2px'},100,function(){
dice.removeClass("dice_t").addClass("dice_s");
}).delay(200).animate({opacity: 'show'},600,function(){
dice.removeClass("dice_s").addClass("dice_e");
}).delay(100).animate({left:'-2px',top:'2px'},100,function(){
dice.removeClass("dice_e").addClass("dice_"+num);
$("#result").html("您擲得點數是<span>"+num+"</span>");
dice.css('cursor','pointer');
$("#dice_mask").remove();//移除遮罩
});
});
});
新聞熱點
疑難解答
圖片精選