簽到抽獎功能——常見前端抽獎需求


網站開發 ,經常需要用到登錄注冊,簽到抽獎等模塊,雖然每次都要寫,但是把這個記錄下來會很方便下次再用。。。

這邊剛寫了一個簽到抽獎,放到這邊來分享記錄一下。 項目地址www.macdown.com

首先根據設計圖 需要這樣的樣式與效果

這樣的抽獎頁面無非就是樣式當前類切換的效果, 那基本邏輯就是點擊抽獎后,需要做一個跑馬燈的效果,並且一開始加速然后減速到出中獎結果, 這邊會用到定時器

每切換一下調用定時器,直到出來結果后清除定時器。。。展示中獎

那面貼上代碼

// 調用是這樣的 

// 聲明這個函數 用來傳入后台請求獲取中獎結果id的
function getId() {
    return Math.ceil(Math.random(1,8)*10) + 7; // 線下測試 隨機數結果
    // return  '   '  // 這里是如果用戶沒有權限抽獎 返回的字符串  
};

const lettery = new Lottery(getId);   //創建實例 ,傳入獲取中獎id的函數,前面還可以傳入一個對象,里面是控制抽獎轉的最低圈數與速度

//模擬后台獎品數據
const prize = [{"id":9,"title":"10個積分","type":1},{"id":10,"title":"5元優惠券","type":2}, ....] 共七組獎品

lettery.init(prize); // 初始化 , 傳入獎品數據 prize

上面是如何調用這個功能 ,下面h+c實現樣式,但並未做注釋,樣式可以自己根據需要去寫,也是簡單的東西,最后是js邏輯代碼,有我的理解與注釋

// 這邊是html 字符串,放在js中,初始化的時候處理並加入頁面

let lotteryHtml = `
        <div id="lottery">
        <div class="lottery-box">
            <div class="lottery-head">
                <h1><img src="../images/sign/sign-box.png" width="40" height="40">簽到抽獎</h1>
                <div class="prize-close">X</div>
            </div>
            <div class="lottery-content">
                <div class="left-light sider-light">
                    <i></i><i></i><i></i><i></i><i></i><i></i><i></i>
                </div>
                <div class="top-light sider-light">
                    <i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i>
                </div>
                <div class="right-light sider-light">
                    <i></i><i></i><i></i><i></i><i></i><i></i><i></i>
                </div>
                <div class="bottom-light sider-light">
                    <i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i><i></i>
                </div>
                <div class="prize-content">
                    <ul class="clearfix">
                        <li class="lottery-0" data-id="{ id }" data-index="0">
                            <img src="{ src }" alt="">
                            <p>{ title }</p>
                        </li>
                        <li class="lottery-1" data-id="{ id }" data-index="1">
                            <img src="{ src }" alt="">
                            <p>{ title }</p>
                        </li>
                        <li class="lottery-2" data-id="{ id }" data-index="2">
                            <img src="{ src }" alt="">
                            <p>{ title }</p>
                        </li>
                        <li class="lottery-7" data-index="7">
                            <p class="thank">謝謝參與</p>
                        </li>
                        <li class="lottery">
                            <p class="title">開始抽獎</p>
                            <span>免費次數:<em>1</em>次</span>
                        </li>
                        <li class="lottery-3" data-id="{ id }" data-index="3">
                            <img src="{ src }" alt="">
                            <p>{ title }</p>
                        </li>
                        <li class="lottery-6" data-id="{ id }" data-index="6">
                            <img src="{ src }" alt="">
                            <p>{ title }</p>
                        </li>
                        <li class="lottery-5" data-id="{ id }" data-index="5">
                            <img src="{ src }" alt="">
                            <p>{ title }</p>
                        </li>
                        <li class="lottery-4" data-id="{ id }" data-index="4">
                            <img src="{ src }" alt="">
                            <p>{ title }</p>
                        </li>
                    </ul>
                    <div class="prize-reason">
                        <div>
                            <span class="close-res">X</span>
                            <p class="res-title"></p>
                            <img src="">
                            <p class="res-con"></p>
                            <span class="res-btn">再抽一次</span>
                        </div>
                    </div>
                </div>
            </div>
            <div class="prize-bottom">
                <div>
                    <h4>抽獎說明:</h4>
                    <p>1、 每個用戶每天簽到一次可獲得一次抽獎機會( 抽獎機會當天有效 )</p>
                    <p>2、 10積分抽獎一次</p>
                </div>
            </div>
        </div>
    </div>
    `; 

// css 可根據自己的需求修改 我這邊是stylus 語法

// 抽獎
#lottery
	position fixed 
	left 0px
	top 0px
	right 0px
	bottom 0px
	background-color rgba(0,0,0,.6)
	z-index 999
	display none
	.lottery-box
		width 440px
		height 620px
		position absolute
		left 0px
		top 0px
		right 0px
		bottom 0px
		margin auto 
	.lottery-head
		width 250px
		height 40px
		line-height 40px
		border-radius 20px
		background-color #353535
		text-align center
		margin 0 auto 
		h1 
			font-size 24px
			margin 0
			color #E97424
			height 40px
			line-height 40px
			img 
				vertical-align middle
				margin-right 10px
				margin-top -20px
	.prize-close
		position absolute
		right -60px
		top -20px
		width 40px
		height 40px
		background-color #3F3F3F
		line-height 40px
		border-radius 50%
		text-align center
		color #fff 
		font-size 20px
		cursor pointer
	.lottery-content
		position relative 
		width 100%
		height 388px 
		margin-top 20px
		border-radius 20px 
		overflow hidden
		background-color #222
		.sider-light
			position absolute
			background-color #353535
			font-size 0
			i 
				display inline-block
				width 10px
				height 10px 
				border-radius 50%
				box-shadow 0 0 20px rgba(204,255,255,.8)
				vertical-align middle
				animation light 1s alternate infinite;
				&:nth-child(2n)
					animation light 1s linear 1s alternate infinite;
		.left-light,.right-light
			width 24px 
			top 24px 
			height 332px
			left 0px
			text-align center
			i 
				display block
				background-color #E97424
				margin 0 auto 38px
				&:first-child
					margin-top 17px
				&:last-child
					margin-bottom 0
				&:nth-child(2n)
					background-color #FDBD40
		.right-light
			left auto 
			right 0px
		.top-light,.bottom-light
			left 0px
			top 0px
			height 24px 
			line-height 24px
			width 100%
			i 
				margin-right 38px 
				background-color #FDBD40
				&:first-child
					margin-left 23px
				&:last-child
					margin-right 0
				&:nth-child(2n)
						background-color #E97424
		.top-light
			border-radius 20px 20px 0 0
		.bottom-light 
			top auto 
			bottom 8px
			border-radius 0 0 20px 20px
		
	.prize-content
		padding 34px
		li 
			float left
			width 120px 
			height 100px 
			border-radius 10px 
			margin-right 6px 
			margin-top 6px 
			background-color #FFF2DA
			border 2px solid transparent
			box-sizing border-box
			cursor default
			text-align center
			&.active 
				border-color #E97424
			&:nth-child(-n+3)
				margin-top 0
			&:nth-child(3n)
				margin-right 0
			&:nth-child(5)
				background-color #E97424
				cursor pointer
				user-select none
				.title
					font-size 23px 
					color #fff 
					margin-top 20px
				span 
					color #FFCC00
			img 
				width 50px
				margin-top 10px
			p 
				color #E97424
			.thank
				line-height 100px
		.prize-reason
			position absolute 
			width 300px
			height 300px
			left 0px
			top 0px
			right 0px
			bottom 0px
			margin auto 
			border-radius 20px 
			background-color #353535
			overflow hidden
			color #fff 
			text-align center
			display none
			&>div 
				position relative 
				z-index 2
			&:before 
				content ""
				position absolute
				width 200%
				height 200%
				border-radius 50%
				left 50%
				margin-left -100%
				top -160%
				background-color #222222
			.close-res
				position absolute
				right 5px
				top 5px 
				width 30px 
				height 30px 
				border-radius 50%
				color #fff 
				text-align center
				line-height 30px 
				background-color rgba(0,0,0,.8)
				cursor pointer
			.res-title
				font-size 24px 
				line-height 60px 
			img 
				margin-top 20px 
			.res-con
				line-height 50px 
				height 50px 
				font-size 22px 
				font-weight bold
				&.no 
					font-size 16px 
					font-weight normal 
			.res-btn 
				display block
				margin 25px auto 0
				width 120px 
				height 34px 
				line-height 34px 
				font-size 16px 
				color #fff
				background-color #FECC32
				border-radius 5px 
				cursor pointer
				user-select none
	.prize-bottom
		margin-top 24px 
		background-color #222222
		width 100%
		height 148px
		border-radius 20px 
		position relative
		&::after,&::before 
			content ""
			position absolute
			width 10px 
			height 24px 
			background-color #353535
			top -24px 
			left 130px 
		&::after 
			left auto 
			right 130px
		div 
			width 100%
			height 140px 
			border-radius 20px
			background-color #353535
			box-sizing border-box
			padding 10px 20px 
			color #ddd 
			line-height 2
			h4 
				font-size 16px 
				color #E97424
		
@keyframes light 
	0% 
		box-shadow 0 0 5px rgba(204,255,255,.8)
	100
		box-shadow 0 0 20px rgba(204,255,255,.8)
		


上面兩段是樣式效果, 下面是邏輯代碼了。

;(function(win, $) {

    //這邊是用到的三張圖片地址  變量沒有大寫。。
    const pointImgSrc = '../images/sign/point.png';
    const couponImgSrc = '../images/sign/coupon.png';
    const thanksImgSrc = '../images/sign/thanks.png';

    /**
        opts => object 
        * speed 轉動速度  數值越小速度越快
        * cycle 最少轉圈數
        
        fn => function 
        * return id (Number)
    */ 
    
    
    class Lottery {
        constructor(fn = 0, opts = {}) { 
            this.opts = opts;
            this.callbackId = fn;
        }

        //初始化
        init(data = []) {  // 傳入獎品數據數組對象 數組長度為7  獎品id, 獎品title, 獎品類型 1,2
            this.options = Object.assign({}, {
                speed: 40,
                cycle: 5,
            }, this.opts);  // 合並默認參數

            // 初始一些變量
            this._index = 0; // 當前轉動位置
            this._timer = null; // 計時器
            this._count = 8; // 抽獎轉動的長度
            this._prize = -1; // 中獎的位置 
            this._times = 0; // 轉動的次數
            this._curId = 0; // 中獎的id 后台提供
            this._speed = this.options.speed;
            this._cycle = this.options.cycle * 8;
            this._isClick = false; 
            this._prizeType = 0; // 中獎類型
            this._prizeTitle;

            this.data = data; // 獎品數據  后台提供

            this._render(); // 渲染抽獎模塊

            this._initEvent(); //初始事件
        }

        _render() {
            let html = '',
                i = 0,
                j = 0,
                k = 0; // 數組賦值索引參數
            
            html += lotteryHtml
                .replace(/{ src }/g, (v)=>{
                    return prize[i++].type == 1? pointImgSrc: couponImgSrc;
                })
                .replace(/{ title }/g, (v)=>{
                    return prize[j++].title;
                })
                 .replace(/{ id }/g, (v)=>{
                    return prize[k++].id;
                })

            $('body').append(html);
            this.lotteryDom = $('#lottery'); //聲明dom對象
        }

        _initEvent() { 
            this.lotteryDom
                .on('click', '.prize-close', ()=> {
                    this.lotteryDom.hide();
                })
                .on('click', '.close-res', ()=> {
                    this.lotteryDom.find('.prize-reason').fadeOut();
                })
                .on('click', '.lottery, .res-btn', this.startGame.bind(this))
        }

        startGame() {
            this.lotteryDom.find('.prize-reason').fadeOut(); // 開始時候隱藏上次中獎結果彈出層
            // 后台請求中獎id   簡單處理非id 直接警告
            if (typeof(this.callbackId()) == 'number') {
                this._curId = this.callbackId(); 
            } else {
                alert(this.callbackId());
                return;
            };

            // if(this.lotteryDom.find('.lottery em').text() == 1) {   // 免費抽獎次數清零。  
            //       this.lotteryDom.find('.lottery em').text(0)
            // }

            if(!this._isClick) {  //  抽獎動畫沒結束 不能再次觸發
                this._roll();
            }
        }

        _getPrizeIndex() {
            // 這里過濾獲取當前中獎結果索引
            let dom = this.lotteryDom.find('li').filter((i,v)=>{
                return $(v).data('id') == this._curId;
            })
               

            this._prizeType = dom.find('p').text().indexOf('積分') > 0? 1: dom.find('p').text().indexOf('優惠券') > 0? 2: 0;
            if(this._prizeType) {
                this._prizeTitle = dom.find('p').text();
            };

            if(!dom.length) return 7; // 全都不符合返回謝謝惠顧的索引

            return dom.data('index')/1; 
        }

        _roll() {
            this._isClick = true; // 控制暴力點擊

            this.lotteryDom.find('.lottery-'+ this._index).removeClass('active');  //每次調用 去除當前選中 
            this._index++;

            if(this._index > this._count - 1) {  // 循環添加
                this._index = 0;
            }

            this.lotteryDom.find('.lottery-'+ this._index).addClass('active');  // 下一個添加選中

            this._times ++;
            if(this._times > this._cycle + 10 && this._prize == this._index) {  // 轉動圈數超過基數+10 並且當前位置等於中獎結果位置
                
                clearTimeout(this._timer); // 清除定時器
                this._showPrize(); // 展示中獎結果
            } else {

                if(this._times < this._cycle) { // 圈數小於設置的基數 速度邊快
                    this._speed -= 10;

                } else if(this._times == this._cycle) {
                    this._prize = this._getPrizeIndex(); // 轉動到達基數時候 獲取中獎結果的索引

                } else {
                    if (this._times > this._cycle + 10 && (this._prize == 0 && this._index == 7 || this._prize == this._index + 1)) {   // 這里是當  當前轉動到的索引是中獎的前一個位置的時候 立刻 減速的判斷條件
                        this._speed += 110;
                    } else {
                        this._speed += 20;
                    }
                }

                if (this._speed < 40) {  // 設置最快速度
                    this._speed = 40
                }

                this._timer = setTimeout(()=>{  // 重復執行
                    this._roll();
                }, this._speed)
            }
        }

        _showPrize() { //展示中獎結果
            // 直接dom操作 展示結果文案了
            let reizeDon = this.lotteryDom.find('.prize-reason');
            reizeDon.fadeIn();
            if(this._prizeType) {
                reizeDon.find('img').attr('src', this._prizeType == 1? pointImgSrc: couponImgSrc);
                reizeDon.find('.res-title').text('恭喜獲得');
                reizeDon.find('.res-con').text(this._prizeTitle).removeClass('no');
            } else {
                reizeDon.find('.res-title').text('謝謝參與');
                reizeDon.find('.res-con').text('哎呀,沒抽中, 換個姿勢,再來一次吧~').addClass('no');
                reizeDon.find('img').attr('src', thanksImgSrc);
            }
            

            // 初始點擊與動畫
            this._isClick = false; 
            this._prize = -1;
            this._times = 0;
            this._speed = this.options.speed;
        }
    }


    win.Lottery = Lottery;

})(window, jQuery);

最后抽獎就是這個結果啦,項目地址在www.macdown.com,效果可以自己在網站中看到哦~

上面展示了如何完成一個抽獎功能, 如果有更好的,希望指出, 因為在練習es6, 所有就混合成這樣的四不像了, jq還是沒有放下。。。 不用框架寫原生真的不想嘗試。。。

就一個前端,我當然是想咋樣咋樣啦~


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM