抽獎活動在營銷中越來越受到重視,為了讓用戶更有趣味性地參與抽獎,使用CSS3來制作抽獎動畫是一個不錯的選擇。
.lottery { width: 300px; height: 300px; background: #fff; border-radius: 50%; position: relative; overflow: hidden; text-align: center; } .lottery:before { content: ""; display: block; position: absolute; bottom: 0; left: -150px; width: 600px; height: 600px; background: #f9a11b; border-radius: 50%; transform: rotate(-45deg) skewY(22.5deg) scale(1.1); z-index: -1; animation: rotateLottery 3s linear infinite; } @keyframes rotateLottery { from { transform: rotate(-45deg) skewY(22.5deg) scale(1.1); } to { transform: rotate(-405deg) skewY(22.5deg) scale(1.1); } } .lotteryButton { width: 150px; height: 50px; border-radius: 25px; background: #f9a11b; color: #fff; line-height: 50px; text-align: center; font-size: 20px; position: absolute; bottom: 20px; left: 50%; margin-left: -75px; cursor: pointer; z-index: 1; } .lottery .lotteryPointer { background: #f00; position: absolute; bottom: 140px; left: 50%; margin-left: -5px; width: 10px; height: 100px; border-radius: 5px; transform-origin: center bottom; transition: transform 3s ease; } .lottery .lotteryResult { position: absolute; top: 40%; left: 50%; margin-left: -75px; width: 150px; height: 50px; border-radius: 25px; background: #f9a11b; color: #fff; line-height: 50px; text-align: center; font-size: 20px; opacity: 0; transition: opacity 1s ease; } .lottery .lotteryResult.show { opacity: 1; }
以上是CSS代碼,其中利用偽元素:before制作了一個圓形的背景,并利用動畫rotateLottery來實現轉動的效果。同時,抽獎按鈕和結果欄也是利用CSS樣式實現的。比如,抽獎指針的樣式利用了transform-origin屬性和transition屬性。
javascript代碼如下:
let lottery = document.querySelector(".lottery"); let lotteryPointer = document.querySelector(".lotteryPointer"); let lotteryButton = document.querySelector(".lotteryButton"); let lotteryResult = document.querySelector(".lotteryResult"); let prize = [ "一等獎", "二等獎", "三等獎", "謝謝參與", "三等獎", "二等獎", "一等獎", "謝謝參與" ]; let deg = [0, 45, 90, 135, 180, 225, 270, 315]; lotteryButton.addEventListener("click", function() { let randomNumber = Math.floor(Math.random() * prize.length); let randomDeg = Math.floor(Math.random() * 45 + 360 * 5 + deg[randomNumber]); lotteryPointer.style.transform = "rotate(" + randomDeg + "deg)"; setTimeout(function() { lotteryResult.textContent = prize[randomNumber]; lotteryResult.classList.add("show"); }, 3000); });
在javascript代碼中,先定義了獎項和對應的角度,然后給抽獎按鈕綁定事件,在點擊事件中,隨機生成一個獎項,并計算出對應的角度,然后通過改變樣式來實現抽獎指針的旋轉,最后延時3秒后顯示獲得的獎品。
下一篇抽獎css設置