標籤:
今天花了一段時間簡單寫了下抽獎大轉盤,這裡寫的只是自己想到的簡單的寫了下(也希望收穫其他想法),後續,再寫的話會更新。
大體思路:頁面載入完成後,通過監聽開始按鈕的點擊事件。然後會根據產生的隨機數,通過控制旋轉針對象的transform屬性,然後進行旋轉,最後在結束後擷取儲存來數組中對應的抽獎內容最後彈出。
知識點:transform, translation,js數組,Math等等
先看下效果,沒有素材,只是用css簡單的布了下局。不要噴我比較簡陋,嘿嘿。
接下來是基本代碼結構:
1 <div class="rotate_con"> 2 <div class="rotate_row"> 3 <div class="rotate_item"> 4 RMB100 5 </div> 6 <div class="rotate_item"> 7 流量100M 8 </div> 9 <div class="rotate_item">10 謝謝參與11 </div>12 </div>13 <div class="rotate_row">14 <div class="rotate_item">15 再接再厲16 </div>17 <div class="rotate_item item_start" id="start">18 開始19 <div class="rotate" id="rotate_zhen">20 21 </div>22 </div>23 <div class="rotate_item">24 RMB225 </div>26 </div>27 <div class="rotate_row">28 <div class="rotate_item">29 RMB10030 </div>31 <div class="rotate_item">32 謝謝參與33 </div>34 <div class="rotate_item">35 流量100M36 </div>37 </div>38 </div>
接下來是樣式:
1 <style> 2 * { 3 margin: 0; 4 padding: 0; 5 } 6 7 .rotate_con { 8 margin: 50px auto; 9 width: 320px;10 height: 320px;11 border: 1px solid #FFFFFF;12 border-radius: 50%;13 }14 15 .rotate_row {16 display: flex;17 display: -webkit-flex;18 height: 33.3333333%;19 }20 21 .rotate_item {22 flex: 0 0 33.3333333%;23 -webkit-flex: 0 0 33.3333333%;24 line-height: 106.666666px;25 text-align: center;26 background: yellow;27 padding: 1px;28 border: 1px solid #fff;29 box-sizing: border-box;30 }31 32 .item_start {33 position: relative;34 background-color: #FF5E5E;35 color: #FFFFFF;36 font-weight: bold;37 cursor: pointer38 }39 40 .item_start:active {41 background: #ED745B;42 }43 44 .rotate {45 position: absolute;46 width: 5px;47 height: 106px;48 top: -53px;49 left: 53px;50 background: #fff;51 transform: rotateZ(0deg);52 transform-origin: left bottom;53 -webkit-transform-origin: left bottom;54 transition: all 1.5s cubic-bezier(0.25, 0.1, 0.25, 1);55 }56 57 .item_active {58 border-color: red;59 }60 </style>
最後js部分
1 <script> 2 //擷取對象 3 var getid = function(id) { 4 return document.getElementById(id); 5 }; 6 //按照旋轉順序的數組 7 var context = ["流量100M", "謝謝參與", "RMB2", "流量100M", "謝謝參與", "RMB100", "再接再厲", "RMB100"]; 8 var deg = 45, //旋轉的預設角度360/8 9 numdeg = 0, //記錄上次旋轉停止時候的角度10 num = 0, //記錄旋轉後數組的位置11 isRotated = false; //判斷是否在進行中12 window.onload = function() {13 var zhen = getid("rotate_zhen");14 getid("start").addEventListener(‘click‘, function() {15 if(isRotated) return; //如果正在旋轉退出程式16 isRotated = true;17 var index = Math.floor(Math.random() * 8); //得到0-7隨機數18 num = index + num; //得到本次位置19 numdeg += index * deg + Math.floor(Math.random() * 3 + 1) * 360;20 zhen.style.webkitTransform = zhen.style.transform = "rotateZ(" + numdeg + "deg)";21 setTimeout(function() {22 if(num >= 8) { //如果數組位置大於7就重新開始23 num = num % 8;24 }25 alert(context[num]);26 isRotated = false; //旋轉改為false說明沒有旋轉27 }, 1700)28 }, false)29 }30 </script>
最後是測試結果:
大轉盤抽獎css3+js(簡單書寫)