前言:之前籠統的學習了angular框架,紙上得來終覺淺,這次自己獨立完成了一個簡單的抽獎單頁。也算是給自己前面的學習一個總結和交代。
界面效果:
業務流程:
首先用戶在首頁點擊抽獎按鈕,進入抽獎界面,紅色磚塊將會快速隨機跳動,最終停在某一個獎品之上,即刻進入抽獎結果頁面。
核心代碼:
初始化獎品
$scope.items = [
{id:1,name:"IPhone7",status:0},
{id:2,name:"現金5000元",status:0},
{id:3,name:"美的電冰箱",status:0},
{id:4,name:"美的微波爐",status:0},
{id:5,name:"牀上四件套",status:0},
{id:6,name:"充電寶",status:0},
{id:7,name:"保溫杯",status:0},
{id:8,name:"蘋果耳機",status:0},
{id:9,name:"50元話費",status:0}
];
其中status用於判斷當前獎品是否顯示被抽中,下面會再提到(當status爲1時顯示爲紅色磚塊)
構造一個類似Jquery的選擇函數
$scope.$$ = function(id){
return document.getElementById(id);
}
隱藏前一個頁面顯示下一個頁面
$scope.showhide = function(pre,next){
pre = "step"+pre;
next = "step"+next;
$scope.$$(pre).style.display = "none";
$scope.$$(next).style.display = "block";
}
抽獎思路
- 點擊抽獎按鈕之後,當前頁面隱藏,抽獎頁面顯示,即先調用函數
showhide(1,2)
- 自定義閃動圈數
var circle = 6;
- 聲明隨機中獎號碼
var luckyKey = Math.floor(Math.random()*$scope.items.length)
- 循環閃動函數
next(0)
開始調用
var next = function(key){
$scope.items[key].status = true;
if((key-1)>=0){
$scope.items[key-1].status = false;
}
if(key==0){
$scope.items[$scope.items.length-1].status = false;
}
var timer = $timeout(function() {
if(circle <= 0 && luckyKey == key){
$scope.showhide(2,3);
$scope.result = $scope.items[key].name;
return;
}
if($scope.items.length == key+1){
circle--;
}
if($scope.items[key+1]){
next(key+1);
}else{
next(0);
}
}, 100);
}